Scoped variables

Andrew Haley aph at
Wed Dec 5 10:15:23 UTC 2018

On 12/4/18 8:32 PM, Doug Lea wrote:
> On 12/4/18 12:12 PM, Andrew Haley wrote:
>> The problem is that the current TheadLocal code is very complex,
>> and if we restrict ourselves to a simple get() we can do better.
> Could you explain? Of the possibilities I'm aware of that might be cheaper:
> * The cheapest version is to access a field of current Thread/Fiber, as
> is possible with Threads by defining Thread subclasses.

We don't have to restrict ourselves to Java code. Digging into the JVM,
there is (usually) a register pointing to the current VM thread metadata.
Thread.currentThread() is a field in that structure.

About half of the code in ThreadLocal.get() is because of bounds
checks, indirections, type checks, and null pointer checks. The null
pointer checks facilitate lazy initialization, which we don't need in
scoped variables. There also some indirections because structures such
as HashMap have to go from the Map itself to its table: current Java
requires it. There are some because of the use of WeakReferences,
which scoped variables won't need because they disappear when the
scope exits. Finally, scoped variables don't need type checks any more
than ordinary field loads do: the VM can enforce that.

Of course, not all of these optimizations need to be done in a first
cut, but any design should IMO allow them.

Andrew Haley
Java Platform Lead Engineer
Red Hat UK Ltd. <>
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671

More information about the loom-dev mailing list