The easiest way to get started is to configure your IDE to use a recent Project Loom 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 rather than the operating system. They Virtual threads are 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.
...
| Code Block |
|---|
|
ThreadFactory factory = Thread.builder().virtual().name("worker", 0).factory(); |
Thread Locals
ExecutorService API
The following creates an ExecutorService that runs each task in its own virtual thread. The example uses the try-with-resources construct to ensure that the ExecutorService is shutdown and that the two tasks (each run in its own virtual thread) complete before continuing.
| Code Block |
|---|
|
try (ExecutorService executor = Executors.newUnboundedVirtualThreadExecutor()) {
executor.execute(() -> System.out.println("Hello"));
executor.execute(() -> System.out.println("Hi"));
} |
This The example below runs three tasks and selects the result of the first task to complete. The remaining tasks are cancelled, which causes the virtual threads running them to be interrupted.
| Code Block |
|---|
|
try (ExecutorService executor = Executors.newUnboundedVirtualThreadExecutor()) {
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> "bar";
Callable<String> task3 = () -> "baz";
String result = executor.invokeAny(List.of(task1, task2, task3));
} |
This following 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 = () -> "foo";
Callable<String> task2 = () -> "bar";
Callable<String> task3 = () -> "baz";
List<CompletableFuture<String>> cfs = executor.submitTasks(List.of(task1, task2, task3));
CompletableFuture.stream(cfs)
.map(CompletableFuture::join)
.forEach(System.out::println);
} |
...