ThreadLocal with null initial values - avoid create map and entry?

Bernd Eckenfels ecki at
Tue Nov 18 14:59:19 UTC 2014

Am Tue, 18 Nov 2014 11:37:34 +0000
schrieb Tom Hawtin <tom.hawtin at>:

> On 18/11/2014 05:11, Bernd Eckenfels wrote:
> > Unfortunatelly the ThreadLocal#get() will call #setInitialValue() in
> > all cases, and this will in turn call createMap(). setInitialValue()
> > could avoid to call createMap() when value is null. This would
> > reduce the number of created thread specific maps and entries (and
> > also weak references to the thread).
> There's no guarantee that the execution of initialValue was trivial
> even if it returns null.

Yes, but I dont think it has to be. As long as the initial value is
null it can be represented without any thread local map or entry. And
as there is no "hasEntry()" a application can only call get to probe
for existence (and this will in the current implementation always
created it).

So another option (but more complicated as it adds a new API function)
would be to have a hasEntry() (or similiar named) function which does
the same as get without calling the initialValue(). This would in this
case really differ for non-trivial initialValue() implementations,
thats why I would prefer to do it in get(). It needs to be checked if
get() gets too big for inlining, but the new if is not in a hot path.


> I don't know whether or not mixing up the execution paths through get 
> would harm performance.
> Tom

More information about the core-libs-dev mailing list