JEP!!! 506: Scoped Values

TL;DR: ThreadLocal for a call scope instead of a whole thread. A value is bound once for a block of code and is visible to all methods executed within that call chain — even in completely sequential code.

General web example :

Example 1 - basic use

Shows how scoped values can help with passing context through call chains

Example 2 - compare to thread local

ThreadLocal allows mutation of ambient context, while ScopedValue allows only temporary rebinding in a nested scope.

For long lived threads - if value from thread local is not removed it may lead to memory leaks.

So something like the following is needed :

scoped value is always cleaned when scope ends. ThreadLocal attaches data to the lifetime of a thread. ScopedValue attaches data to the lifetime of a call.

And if youa re using thread pool and forget to cleanup ThreadLocal then data may leak between requests - security,security,security!

Example 3 - understand scope

Example show how scope works.

some examples for scope related method use :

Example 4 - nested scopes

Example 5 - structured concurrency preview

Thanks to immutable nature all vierual threads which by design are lightweight and may be many of them - don't need dedicated ThreadLocal instance which would allocate memory

Last updated