The easiest way to get started is to configure your IDE to use a recent Project Loom JDK 19 Early Access (EA) build and get familiar with using the java.lang.Thread API to create a virtual thread to execute some code. Virtual Threads threads are just threads that are scheduled by the Java virtual machine JDK rather than the operating system. TheyVirtual threads are best suited to executing code that spends most of its time blocked, maybe waiting for a data to arrive on a network socket . Virtual threads are not suited to running code that is compute bound.or waiting for an element in queue for example.
Many applications won't use the Thread API directly but instead will use the In addition to to the Thread API, the java.util.concurrent.ExecutorService and Executors APIs are have . The Executors API has been updated to make it easy to work with virtual threadswith new factory methods for ExecutorServices that start a new thread for each task. Virtual threads are cheap enough that a new virtual thread can be created for each task, no need for pooling of there should never be a need to pool virtual threads.
Thread API
The following uses a static factory method to start a virtual thread. It invokes starts a virtual thread to print a message. It invokes the join method to wait for the thread to terminate.
| Code Block |
|---|
|
Thread thread = Thread.startVirtualThreadofVirtual().start(() -> System.out.println("Hello"));
thread.join(); |
The Thread.Builder API can also be used to create virtual threads that are configured at build. The first snippet below creates an un-started thread. The second example creates and starts with thread name "bob"following is an example that start a virtual thread to put an element into a queue after sleeping. The main thread blocks on the queue, waiting for the element.
| Code Block |
|---|
|
Thread thread1 var queue = Thread.builder().virtualnew SynchronousQueue<String>();
Thread.ofVirtual().taskstart(() -> System.out.println("Hello")).build();
Thread thread2 = Thread.builder()
{
try {
Thread.sleep(Duration.virtualofSeconds(2));
.namequeue.put("bobdone");
} catch (InterruptedException e) { }
.task(() -> System.out.println("I'm Bob!")) });
String msg .start= queue.take(); |
The Thread.Builder API can also be used to create a ThreadFactory. The ThreadFactory created by the following snippet will create virtual threads named "worker-0", "worker-1", "worker-2", ...
| Code Block |
|---|
|
ThreadFactory factory = Thread.builderofVirtual().virtual().name("worker", 0).factory(); |
Executors/ExecutorService API
The following creates example uses the Executors API to create an ExecutorService that runs starts a new virtual thread for each task in its own virtual thread T.he . The example uses the try-with-resources construct to ensure that the ExecutorService is shutdown and that the two tasks (each run by a virtual thread) complete before continuing.the ExecutorService has terminated before continuing.
ExecutorService defines submit methods to execute tasks for execution. The submit methods don't block, instead they return a Future object that can be used to wait for the result or exception. The submit method that takes a collection of tasks returns a Stream is lazily populated with completed Future objects representing the results.
The example also uses the invokeAll and invokeAny combinator methods to execute several tasks and wait them to complete.
| Code Block |
|---|
|
try (ExecutorService executor = Executors.newUnboundedVirtualThreadExecutornewVirtualThreadExecutor()) {
executor.execute(() -> System.out.println("Hello"));
executor.execute(() -> System.out.println("Hi"));
} |
This example runs three tasks and selects the result of the first task to complete. The remaining tasks are cancelled, which causes the virtual threads running it to be interrupted.
| Code Block |
|---|
|
try (ExecutorService executor = Executors.newUnboundedVirtualThreadExecutor()) {
Callable<String> task1 = ( // Submits a value-returning task and waits for the result
Future<String> future = executor.submit(() -> "foo");
Callable<String> task2 = () -> "bar";
String Callable<String> task3result = future.join() -> "baz";
;
String result = executor.invokeAny(List.of(task1, task2, task3));
} |
This example uses submitTasks to submit three value returning tasks. It uses the CompletableFuture.stream method to obtain a stream that is lazily populated as the tasks complete.
| Code Block |
|---|
|
try (ExecutorService executor = Executors.newUnboundedVirtualThreadExecutor()) {
Callable<String> task1 = (// Submits two value-returning tasks to get a Stream that is lazily populated
// with completed Future objects as the tasks complete
Stream<Future<String>> stream = executor.submit(List.of(() -> "foo";
Callable<String> task2 = , () -> "bar"));
Callable<String> task3 = stream.filter() -> "baz";Future::isCompletedNormally)
List<CompletableFuture<String>> cfs = executor.submitTasks(List.of(task1, task2, task3));
CompletableFuture.stream(cfs)
.map(CompletableFutureFuture::join)
.forEach(System.out::println);
} |
The following creates an ExecutorService that runs each task in its own virtual thread with a deadline. If the deadline expires before the executor has terminated then the thread executing this code will be interrupted and any tasks running will be cancelled. (which causes the virtual thread to be interrupted).
| Code Block |
|---|
|
Instant deadline = Instant.now().plusSeconds(30);
try (ExecutorService executor = Executors.newUnboundedVirtualThreadExecutor().withDeadline(deadline)) {
:
} |
Appendix: Differences between regular Threads and virtual Threads
The following is a list of the subtle differences between the two types of thread:
...
// Executes two value-returning tasks, waiting for both to complete
List<Future<String>> results1 = executor.invokeAll(List.of(() -> "foo", () -> "bar"));
// Executes two value-returning tasks, waiting for both to complete. If one of the
// tasks completes with an exception, the other is cancelled.
List<Future<String>> results2 = executor.invokeAll(List.of(() -> "foo", () -> "bar"), /*waitAll*/ false);
// Executes two value-returning tasks, returning the result of the first to
// complete, cancelling the other.
String first = executor.invokeAny(List.of(() -> "foo", () -> "bar"));
} |