ThreadLocal with null initial values - avoid create map and entry?
Bernd Eckenfels
ecki at zusammenkunft.net
Tue Nov 18 05:11:08 UTC 2014
Hello,
while debugging and optimizing some application ThreadLocal code I
noticed, that if I not use the initialValue() method for filling a
start value, I could often use the null value to shortcut processing.
I.e. I would add a object with some state to clean up, but if there is
no object, I know I dont have to clean up anything (and I dont need to
create one).
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).
I think not setting the entry is not a problem, as it happens always
single threaded. Bucket conflicts should also be detected in the same
way. I also think that the concurrently used createMap() is already
racing with remove(), so it does not hurt.
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 }
I am not sure if InheritableThreadLocal would need to overwrite this
and skip the optimization?
Gruss
Bernd
More information about the core-libs-dev
mailing list