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

Bernd Eckenfels ecki at zusammenkunft.net
Tue Nov 18 16:07:06 UTC 2014


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

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

Ok, this would makes the hasEntry() more attractive (meaning,
only new and aware applications will have the benefit of saving):

/**
 * Does the current thread local variable exist.
 * <p>
 * This returns false if the thread local was never set
 * or @{link #remove() removed}. The next @{link#get()} 
 * would call @{link #initialValue()} or the and create a map
 * and entry.
 * <p>
 * If true is retruned the entry was initialized or set,
 * but the value might be null.
 * <p>
 * This can be used before calling @{link #get} to further
 * delay initialisation (especially when working with null as initial
 * value).
 */
public boolean hasEntry()
{
  Thread t = Thread.currentThread();
  ThreadLocalMap map = getMap(t);
  if (map == null)
    return false;
  ThreadLocalMap.Entry e = map.getEntry(this);
  return (e != null);
}

(Name is u for discussion, I prefer hasEntry over hasValue as it makes
it clearer that an entry itself might exist but have a null value.
Another common name is I guess exists() with the same issue.

Gruss
Bernd



More information about the core-libs-dev mailing list