r/java • • Apr 06 '22

JEP 425: Virtual Threads (Preview)

https://openjdk.java.net/jeps/425
175 Upvotes

50 comments sorted by

View all comments

3

u/TheMode911 Apr 07 '22

Virtual threads support thread-local variables (ThreadLocal) and inheritable thread-local variables (InheritableThreadLocal), just like platform threads, so they can run existing code that uses thread locals. However, because virtual threads can be very numerous, use thread locals after careful consideration. In particular, do not use thread locals to pool costly resources among multiple tasks sharing the same thread in a thread pool. Virtual threads should never be pooled, since each is intended to run only a single task over its lifetime. We have removed many uses of thread locals from the java.base module in preparation for virtual threads, to reduce memory footprint when running with millions of threads.

What is the replacement for costly resources then? Do we have to wait for ScopeLocal?

1

u/Slanec Apr 07 '22

The most obvious solution is to pool the expensive and limited resource, think a db connection pool. Other options include: Don't use virtual threads if you don't have the memory maybe? Or limit the number of in-flight requests? Or maybe try pooling the virtual threads. I know they're not supposed to be pooled at all, but in this case ... maybe?

If you have a workload like this that (ab)uses thread locals and with thread pool to limit the number of a very costly resource, give loom ea builds a try and provide feedback!

2

u/TheMode911 Apr 07 '22

Pooling requires an additional release mechanism which get annoying pretty fast. What we need here is a new type of ThreadLocal that is strictly linked to the OS (and not a java thread).

Perhaps that this is achievable using panama's foreign api

3

u/kaperni Apr 07 '22

What exact problem are you trying to solve? Seems to me that Java is doubling down on try-with-resources/explicit deallocation with the removal of finalization, introduction of something like ResourceScope in Panama, and various other APIs that have been added lately.