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

Chris Hegarty chris.hegarty at
Tue Nov 18 15:36:09 UTC 2014

On 18/11/14 15:14, Bernd Eckenfels wrote:
> Am Tue, 18 Nov 2014 15:12:46 +0000
> schrieb Chris Hegarty <chris.hegarty at>:
>> 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.

Yes, that was my initial thought too, but unfortunately initialValue 
specifies that the default implementation returns null :-(  So it would 
require a specification change too, and it might be surprising to a 
number of existing applications that rely on this default behavior.


> 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