With the release of JDK 25, I'm curious about whether I should migrate from using ThreadLocal to ScopedValue. I'm not talking about InheritableThreadLocal, just the standard ThreadLocal. My goal is to store transaction and user info per request, which is pretty common. Is making the switch to ScopedValues worth it? What kind of memory savings can I expect, if any? Also, how do they compare in terms of performance?
2 Answers
That's an interesting question! Personally, I'm more focused on how ScopedValues stack up against ThreadLocal when it comes to performance rather than just memory savings. What do you think?
ScopedValues are generally seen as more efficient, but honestly, don’t rush to optimize unless you see it as a bottleneck in your profiling. For example, if operation X is drastically faster than Y and your app uses Y, swapping to X wouldn't be worth your time if it barely impacts performance. You need to assess where ThreadLocal stands in your memory and CPU profile. If it’s a small part, you can take your time, and remember that ScopedValue helps avoid accidental leaks with task management in thread pools.
Could you go into more detail? Why might ThreadLocal have different performance characteristics compared to ScopedValue? And what about memory usage?
Good point! I’m definitely curious about that too.