Java 19: Virtual Threads

Pubblicato il: 24 luglio 2022
sul canale di: Vincent Vauban
359
3

Java 19 preview:
Virtual Threads



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
(bad)
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.

With semaphore
(good)
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 !

With synchronization
(bad)
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.

With ReentrantLock
(good)
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.



CREDITS
https://blogs.oracle.com/javamagazine...

   • Java 19 Virtual Threads - JEP Café #11  

MUSIC
http://ccmixter.org/files/Robbero/65280


In questa pagina del sito puoi guardare il video online Java 19: Virtual Threads della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Vincent Vauban 24 luglio 2022, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 359 volte e gli è piaciuto 3 spettatori. Buona visione!