Java Scoped Values: Better ThreadLocals

submited by
Style Pass
2024-04-24 13:00:10

Largely motivated by Virtual Threads, a new lightweight thread-local alternative has been introduced with the incubation JEP-429 called ScopedValues. ScopedValue is purpose-built to provide a lighter-weight alternative to ThreadLocal that works well with virtual threads and also solves multiple API shortcomings of the twenty-five year old counterpart. This article will dive in to how ScopedValue is different, and how it is made faster under the covers.

Overall, the JEP does an excellent job of explaining the motivational benefits of ScopedValue over ThreadLocal. It can briefly be re-summarized with a few key bullet points:

Because of the different API approach, it is explicitly stated that ScopedValue is not meant to replace all cases for which a ThreadLocal might be used; just those common scenarios where thread locals are used for capturing per-thread context:

There are a few scenarios that favor thread-local variables. An example is caching objects that are expensive to create and use, such as instances of java.text.DateFormat. Notoriously, a DateFormat object is mutable, so it cannot be shared between threads without synchronization. Giving each thread its own DateFormat object, via a thread-local variable that persists for the lifetime of the thread, is often a practical approach.

Leave a Comment