Project Loom in java
Project
loom offers you a lightweight concurrency model. This can be achieved by the
concept of “Virtual threading”. Java includes this in JDK 21.
What is virtual thread?
It is a
lightweight process managed by virtual machine. It is similar process of
threads in Operating system. But specialty is memory allocation and number of
tasks handling is very higher than normal OS.
Features of virtual thread:
- · It is preemptive.
- · It handles millions of tasks.
- · Memory is allocated quickly.
- · It hops over the processors.
- · Memory mapping is shared among virtual threads.
- · Concurrency and parallelism is possible.
How to create java program to illustrate Project loom using
virtual thread??
It
creates VThreadEg class.
Steps to follow:
- · Include the built-in packages java. util.concurrent.ExecutorService,java.util.concurrent.Executors, java.util.stream.IntStream;
- · Create the class VThreadEg and include the main () function.
- · Creating an object for ExecutorService and call virtualthreadpertaskexecutor.
- · Next, Submit lakhs of tasks to the executor.
- · Just make the thread to sleep for time for a blocking operation.
- · Finally,close the task.
Program:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class VThreadEg {
public static void
main(String[] args) {
// Creating an
object for ExecutorService
ExecutorService
executor = Executors.newVirtualThreadPerTaskExecutor();
// Submitting lakhs
of tasks to the executor
IntStream.range(0, 100_000).forEach(i -> executor.submit(() -> {
try {
// a
blocking operation is modelled here
Thread.sleep(115);
System.out.println("Task " + i + " completed");
} catch
(InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
// this code
close the task.
executor.shutdown();
}
}
While executing this program, you will get the below output.
C:\raji\blog>javac VThreadEg.java
C:\raji\blog>java VThreadEg
Task 0 completed
Task 6 completed
Task 8 completed
Task 7 completed
Task 9 completed
Task 11 completed
Task 12 completed
Task 1 completed
Task 13 completed
Task 15 completed
Task 3 completed
Task 18 completed
Task 4 completed
Task 23 completed
Task 24 completed
Task 26 completed
Task 2 completed
Task 28 completed
Task 30 completed
Task 5 completed
Task 34 completed
Task 10 completed
Task 33 completed
Task 37 completed
Task 14 completed
Task 36 completed
Task 38 completed
Task 17 completed
Task 42 completed
Task 16 completed
Task 44 completed
Task 45 completed
Task 19 completed
Task 53 completed
Task 52 completed
Task 20 completed
Task 59 completed
Task 61 completed
Task 21 completed
Task 68 completed
Task 66 completed
Task 88 completed
This program executes the project loom using virtual threading. This gives you high throughput.
No comments:
Post a Comment