Java 19 preview: Virtual Threads
Loom's virtual threads are one of the most anticipated features of the #JDK19. See them in action in my last video
Operating systems can’t increase the efficiency of platform threads, but the JDK will make better use of them by severing the one-to-one relationship between its threads and OS threads.
A virtual thread is an instance of java dot lang dot thread that requires an OS thread to do CPU work -- but doesn’t hold the OS thread while waiting for other resources.
Don’t pool virtual threads!
With thread pool
Suppose you have several hundreds of queries to launch. What you can do is create an executor service with 10 threads, Submit your hundred of queries to this executor service, and it will nicely send them to your database, 10 at a time.
Instead, what you can do is just use a classical Semaphore, that will do exactly the same.
And in fact, if you check the code, you can see that it is simpler, and far more expressive.
With a Semaphore, your code is shouting "I don't want to launch more than 10 queries on this DB at the same time".
Avoid frequent and long-lived pinning !
Now the thing is, for the moment, if a virtual thread is executing some code inside a synchronized block, it cannot be detached from its platform thread.
So during the time it is running this synchronized block of code, it blocks a platform thread.
If this time is long, that is, if it's doing some long I/O operation, you may need to do something.
You can prevent this situation from happenning by simply replacing the call to synchronized() with a reentrant lock.
This problem with synchronized blocks may be solved in the future, so in fact it may be solved by the time virtual threads become a final feature of the JDK.