- Loading...
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 are just threads that are scheduled by the Java virtual machine rather than the operating system. 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.
In addition to to Many applications won't use the Thread API , the directly but instead will use 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 that create ExecutorService to start a 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.
The following uses a static factory method to start a virtual thread. It invokes the join method to wait for the thread to terminate.
...
The following example uses the Executors API to create an ExecutorService that runs each task in its own virtual thread. The example uses the try-with-resources construct to ensure that the ExecutorService has terminated before continuing. The example demonstrates the use of the submit methods (these methods do not block), and the invokeAll/invokeAny combinator methods that execute several tasks and wait them to complete.
...