ThreadLocal lookup elimination
Andrew Haley
aph at redhat.com
Sat Mar 6 13:24:00 UTC 2021
On 3/5/21 7:13 PM, Eirik Bjørsnøs wrote:
> My layman (perhaps naive?) thinking was that a JIT could cheat and infer
> this by definition. Since a ThreadLocal holds memory that is by definition
> local to the executing thread, a JIT should have exclusive access to the
> content of the ThreadLocal. Any back-to-back set/get (or get/get) should
> therefore yield the same value (because no other thread can update the
> contents of the ThreadLocal).
Mostly, but I think that ThreadLocal.createInheritedMap is called
from the Thread constructor.
> However, the JMM doesn't seem to mention ThreadLocals explicitly, so
> perhaps a JIT would need to look at the implementation.. As a programmer I
> would certainly be somewhat surprised if a ThreadLocal get yielded another
> value than my immediately preceding set, or if my two consecutive gets
> would yield different values.
>
> What kind of access patterns could you see breaking this assumption?
> Reflective access into Thread.threadLocals internals by clever frameworks,
> similar to how final fields aren't really final?
There's that, but there's also the issue that ThreadLocalMap entries
are WeakReferences. We don't want to keep a ThreadLocal alive
beyond the lifetime of its key, and this considerably complicates
optimizing ThreadLocals.
The cache (in Loom) Vladimir pointed you to is part of my design
for scope locals, and it can be (and currently is) optimized in
the way you want.
--
Andrew Haley (he/him)
Java Platform Lead Engineer
Red Hat UK Ltd. <https://www.redhat.com>
https://keybase.io/andrewhaley
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671
More information about the core-libs-dev
mailing list