Java Virtual Threads

Today, every instance of java.lang.Thread in the JDK is a platform thread. A platform thread runs Java code on an underlying OS thread and binds the OS thread for the code's entire lifetime. The number of platform threads is limited to the number of OS threads. OS Processes can run multiple OS threads and the number of platform threads correspond to these OS threads. A Virtual thread is an instance of java.lang.Thread that is a lightweight implementation of threads that is provided by the JDK rather than the OS and it runs Java code on an underlying OS/Platform thread.It does not capture/bind the OS thread for the code's entire lifetime. This means that multiple java virtual threads can run on the same OS thread, effectively sharing it. While a platform thread monopolizes/captures/binds/consumes a precious OS thread for the code's entire lifetime.A virtual thread does not consume the entire OS Thread but instead it shares it. They are a form of user-mode threads, which have been successful in other multithreaded languages (e.g., goroutines in Go and processes in Erlang). Earlier there was only One OS process and the java threads used to share this common OS thread. Then the structure of the OS process changed and Platform threads were created which out-performed the single OS thread model. However, Java's green threads all shared one OS thread (M:1 scheduling) green thread model JT1,JT2,JT3 ->OST1 Platform thread model JT1,JT2,JT3->PT1,PT2 and were eventually outperformed by platform threads, implemented as wrappers for OS threads (1:1 scheduling). Virtual threads employ M:N scheduling, where a large number (M) of virtual threads is scheduled to run on a smaller number (N) of OS threads Developers can choose whether to use virtual threads or platform threads. Here is an example program that creates a large number of virtual threads. The program first obtains an ExecutorService that will create a new virtual thread for each submitted task. It then submits 10,000 tasks and waits for all of them to complete: try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { IntStream.range(0, 10_000).forEach(i -> { executor.submit(() -> { Thread.sleep(Duration.ofSeconds(1)); return i; }); }); } // executor.close() is called implicitly, and waits The task in this example is simple code — sleep for one second — and modern hardware can easily support 10,000 virtual threads running such code concurrently. Behind the scenes, the JDK runs the code on a small number of OS threads, perhaps as few as one..

Comments

Popular posts from this blog

Hibernate Many to Many Relationship

Why Integral Calculus limit tending to infinity a sacrilege

Introduction