Reading Time: 2 minutes
If you’d like to create a large number of processes in a cheap way, these processes must run in a concurrent way so that a scale is achieved for a large number of requests processing. To understand in which scenario the Thread needs to scale, let us look at an example below.
Concurrency Example
- HTTP requests
- processing messages from the queue
- integrating external services
- orchestrating workflows
- background jobs
Thread – a current unit of concurrency
Thread thread = new Thread("My Thread") {
public void run(){
System.out.println("run by: " + getName());
}
};
thread.start();
System.out.println(thread.getName());
Currently, the basic unit of concurrency is a THREAD
- Problems with Thread
- expensive to create
- expensive to switch
- limited in number results in limited concurrency
- Solutions
- created upfront
- Problems with Thread Pooling
- expensive to switch
- limited in number results in limited concurrency
- Problems with Thread Pooling
- CompletableFuture – Run tasks in a separate thread and notify the main thread about the progress
- Advantage with CompletableFuture
- cheap to create
- cheap to switch
- unlimited in number results in unlimited concurrency (heap memory)
- Problems with CompletableFuture
- lost control flow
- lost context
- viral
- Advantage with CompletableFuture
- created upfront
What is Project Loom
Project Loom aims to provide a lightweight concurrency tool in Java through virtual threads abstraction.
Virtual Threads – They are just like threads with the difference that they are not exactly a physical OS thread.
- An instance of java.lang
- Multiple virtual threads can run their java code on the same OS thread
Thread t = Thread.startVirtualThread(t) -> { ... };
Creating a Virtual Thread
Thread.startVirtualThread(() -> { System.out.println("Hello World"); });
Difference between Thread and Virtual Thread
- Thread is managed by OS, Virtual threads are managed by the virtual machine, There we can call that there is no 1-to-1 correspondence between the number of virtual threads you are spawning and how they mapped to actual physical threads behind the scene. It is just providing you with a basic unit of concurrency provided by an actual thread at the JVM level. Now, this can be revolutionary when it comes to creating a very large number of concurrent compute units and scaling to a million without worrying about the resources.
1 thought on “Project Loom: Threads Vs Virtual Threads2 min read”
Comments are closed.