Creating Virtual Threads
Thread.ofVirtual and executors.
Creating Virtual Threads is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Ways to Create Virtual Threads
Java offers several entry points for creating virtual threads. The two most important are the Thread.ofVirtual() builder and the Executors.newVirtualThreadPerTaskExecutor() factory.
This lesson walks through each.
The Builder: start
Thread.ofVirtual() returns a builder. Calling .start(runnable) creates and immediately starts the thread.
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.ofVirtual().start(() ->
System.out.println("Started directly"));
t.join();
}
}The Builder: unstarted
Use .unstarted(runnable) when you want to configure the thread and start it later.
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.ofVirtual().unstarted(() ->
System.out.println("Started later"));
System.out.println("Before start, alive? " + t.isAlive());
t.start();
t.join();
}
}A Reusable Factory
The builder can produce a ThreadFactory via .factory(). Each call to newThread yields a fresh virtual thread.
import java.util.concurrent.ThreadFactory;
public class Main {
public static void main(String[] args) throws InterruptedException {
ThreadFactory factory = Thread.ofVirtual().name("job-", 0).factory();
Thread a = factory.newThread(() ->
System.out.println(Thread.currentThread().getName()));
Thread b = factory.newThread(() ->
System.out.println(Thread.currentThread().getName()));
a.start(); b.start();
a.join(); b.join();
}
}The Convenience Method
Thread.startVirtualThread(runnable) is shorthand for creating and starting an unnamed virtual thread in one call.
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.startVirtualThread(() ->
System.out.println("One-liner virtual thread"));
t.join();
}
}The Executor Approach
For task-oriented code, prefer Executors.newVirtualThreadPerTaskExecutor(). It creates a fresh virtual thread for every submitted task.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
try (ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor()) {
exec.submit(() -> System.out.println("task one"));
exec.submit(() -> System.out.println("task two"));
}
System.out.println("All tasks submitted and completed");
}
}Why try-with-resources
Since Java 19, ExecutorService implements AutoCloseable. Closing it in a try-with-resources block waits for all submitted tasks to finish.
This gives you clean, structured shutdown without manual shutdown and awaitTermination calls.
Submitting Many Tasks
The per-task executor effortlessly handles huge task counts. Each task gets its own virtual thread.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
AtomicInteger sum = new AtomicInteger();
try (ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 1; i <= 1000; i++) {
final int n = i;
exec.submit(() -> sum.addAndGet(n));
}
}
System.out.println("Sum 1..1000 = " + sum.get());
}
}Collecting Results with Future
submit returns a Future, so you can collect return values just like with any executor.
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
try (ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor()) {
Future<Integer> f = exec.submit(() -> 6 * 7);
System.out.println("Result: " + f.get());
}
}
}Builder vs Executor
Choose based on intent:
- Builder / startVirtualThread for one-off threads or custom naming
- newVirtualThreadPerTaskExecutor for submitting collections of tasks and collecting results
Both create one virtual thread per unit of work, which is exactly what you want.
Never Cache a Virtual Executor
Do not reuse a single virtual-thread executor as if it were a fixed pool of workers. The executor itself is fine to reuse, but remember each task spawns a brand-new thread.
The point is: there is no pooling of the threads, only convenient task submission.
Quick Check
Pick the best way to run a large batch of tasks, each on its own virtual thread.
Recap
You now know how to create virtual threads:
Thread.ofVirtual().start(...)and.unstarted(...)Thread.startVirtualThread(...)one-liner.factory()for a reusableThreadFactoryExecutors.newVirtualThreadPerTaskExecutor()with try-with-resources
Next: choosing between platform and virtual threads.
Frequently asked questions
Is the “Creating Virtual Threads” lesson free?
Yes — the full text of “Creating Virtual Threads” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Creating Virtual Threads”?
Thread.ofVirtual and executors. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Creating Virtual Threads” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- What Are Virtual Threads
- Creating Virtual Threads
- Platform vs Virtual Threads
- Pitfalls: Pinning and ThreadLocals