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

Bernd Eckenfels ecki at zusammenkunft.net
Tue Nov 18 15:14:04 UTC 2014


Am Tue, 18 Nov 2014 15:12:46 +0000
schrieb Chris Hegarty <chris.hegarty at oracle.com>:

> Interesting idea. If this was to be the case woultn't multiple get() 
> invocations cause multiple initialValue() invocations?
> 
> I think storing the null is important to obey the initialValue /
> remove contract, i.e. initialValue method is invoked at most once per
> thread, but it may be invoked again in case of subsequent invocations
> of remove() followed by get().

Yes, either the contract has to change, or the empty
default implementation of initial value is changed to not return null
but INITIAL.

final static protected Object INITIAL = new Object();
initialValue() { return INITIAL; }
...
if (value != INITIAL)
  createMap();

This way a overwritten initialValue() is still called only after
remove() and only for a unaltered ThreadLocal the optimization applies.

Gruss
Bernd



More information about the core-libs-dev mailing list