In this tutorial we'll see what are virtual threads in Java which are added in Java 21.
Platform threads
Traditional threads which we created till now by implementing Runnable, extending Thread class or by using Executor Service to create thread pools are now known as Platform threads. So, you can say now we have two types of threads which you can create.
- Platform Thread
- Virtual Thread
When a thread is started, it is scheduled by JVM to run (Thread goes to runnable state) but actual execution of the thread is done by the underlying OS by mapping the platform thread to OS thread. A platform thread is implemented as a thin wrapper around an operating system (OS) thread which means number of available platform threads is limited to the number of OS threads. In other words, you can say scalability of platform threads is limited by the number of available OS threads.
Virtual threads in Java
Virtual threads are also an instance of java.lang.Thread
so that way these threads are similar to platform threads. How they differ from platform thread is that virtual threads are implemented by the Java runtime rather than the OS.
Unlike platform thread a virtual thread isn't tied to a specific OS thread which means number of virtual threads is not limited by OS threads. You can have a lot of active virtual threads, even millions, running in the same Java process.
That is the advantage of virtual threads, they provide scale (higher throughput).
How does Virtual thread execute
A virtual thread still runs code on an OS thread, whole process goes as explained below-
- The Java runtime schedules a virtual thread
- Java runtime assigns or mounts the virtual thread on a platform thread. This platform thread is called a carrier
- The underlying OS schedules that platform thread by mapping it to OS thread.
- Virtual thread starts its execution. If the mounted virtual thread is performing a blocking I/O operation it can unmount from its carrier.
- Now the carrier is free and Java runtime scheduler can mount a different virtual thread on it.
When to use Virtual threads
Platform threads generally have a large thread stack and other resources that are maintained by the OS whereas virtual threads typically have a shallow call stack which means virtual threads are light weight but that doesn't mean they are any faster than platform threads.
What virtual threads provide is scale not speed. Virtual threads are suitable for running tasks that spend most of the time blocked, often waiting for I/O operations to complete. However, they aren't intended for long-running CPU-intensive operations.
How to create Virtual threads in Java
1. Using startVirtualThread(Runnable task) method
In Thread class there is a static method startVirtualThread(Runnable task) which creates a virtual thread to execute a task and schedules it to execute.
public class VTDemo { public static void main(String[] args) { Runnable r = () -> System.out.println("Running a task"); Thread virtualThread = Thread.startVirtualThread(r); try { virtualThread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2. Using ofVirtual() method of Thread class
This method returns a builder for creating a virtual Thread or ThreadFactory that creates virtual threads.
public class VTDemo { public static void main(String[] args) { Runnable r = () -> System.out.println("Running a task"); Thread virtualThread = Thread.ofVirtual().start(r); try { virtualThread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Thread.Builder interface has two subinterfaces
- Thread.Builder.OfPlatform- Builder of platform threads.
- Thread.Builder.OfVirtual- Builder of virtual threads.
Thread.Builder example
public class VTDemo { public static void main(String[] args) { Runnable r = () -> System.out.println("Running a task"); Thread.Builder builder = Thread.ofVirtual(); // set the name for threads builder.name("worker-", 0); Thread t1 = builder.start(r); Thread t2 = builder.start(r); try { t1.join(); t2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(t1.getName() + " terminated"); System.out.println(t2.getName() + " terminated"); } }
ThreadFactory of virtual thread example
Thread.Builder has a factory() method that returns a ThreadFactory to create threads from the current state of the builder.
Executors class has methods like newFixedThreadPool(), newCachedThreadPool() which take ThreadFactory as parameter.
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; public class VTFactoryDemo { public static void main(String[] args) { ThreadFactory virtualThreadFactory = Thread.ofVirtual().factory(); ExecutorService es = Executors.newFixedThreadPool(5, virtualThreadFactory); Callable<String> c = () -> "Call from thread"; Future<String> f = es.submit(c); try { System.out.println(f.get()); } catch (InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } es.shutdown(); } }
3. Executors.newVirtualThreadPerTaskExecutor() Method
This method creates an Executor that starts a new virtual Thread for each task. The number of threads created by the Executor is unbounded.
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class VTFactoryDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { try (ExecutorService es = Executors.newVirtualThreadPerTaskExecutor()) { Callable<String> c = () -> "Call from thread"; Future<String> f = es.submit(c); System.out.println(f.get()); } } }
Source: https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html
That's all for this topic Virtual Threads in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-