3 ms·
> However, due to the large number of virtual threads that can be created, developers should use thread-local variables with caution. What is the problem here?
by layer8 4y ago
> However, due to the large number of virtual threads that can be created, developers should use thread-local variables with caution.
What is the problem here? Just the per-virtual-thread memory consumption by the variable when it is used (which would be expected)?
- nicktelford 4y agoLock contention IIRC
- the-alchemist 4y agoYeah, poor performance and memory usage. In the Java world, thread locals are java.lang.ThreadLocal, basically a hashmap from thread to variable. Using a ThreadLocal is (usually) a code smell. It's optimized / supposed to be used with just a few threads, not millions.
- kaba0 4y agoFor what it worth, there actually is a separate JEP (I believe this: https://openjdk.org/jeps/429 https://openjdk.org/jeps/429 ) for a new, scope-bases solution that promises much better performance.
- deleted 4y ago[deleted]
- layer8 4y agoBut the lock would only need to be per platform thread?
- royjacobs 4y agoTypically ThreadLocals are used whenever something is costly to initialize per-request. The rule of thumb is usually: you might want to use some heavy object without locking, so you stick into a ThreadLocal. However, if suddenly you have a million threads then this optimization doesn't work anymore. Sure, the concept of ThreadLocal still works, but in practice you'll end up creating a million of these heavy objects - something you wanted to avoid!
- layer8 4y agoExpensive to initialize doesn’t imply large. And wanting to avoid expensive initialization (runtime) is orthogonal to wanting to avoid a larger memory footprint. So I don’t quite buy your argument.
- royjacobs 4y agoYour question was why the advice was given to avoid ThreadLocals. This is the primary reason. It's not necessarily related to avoiding a larger memory footprint.