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

Chris Hegarty chris.hegarty at oracle.com
Tue Nov 18 15:12:46 UTC 2014


On 18/11/14 05:11, Bernd Eckenfels wrote:
> ....
> What do you think? (code from OpenJDK 8:)
>
> 179    private T setInitialValue() {
> 180        T value = initialValue();
> 181        Thread t = Thread.currentThread();
> 182        ThreadLocalMap map = getMap(t);
> 183        if (map != null)
> 184            map.set(this, value);
> 185        else
> +++            if (value != null)
> 186                createMap(t, value);
> 187        return value;
> 188    }

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().

-Chris.



More information about the core-libs-dev mailing list