Java – is ThreadLocal thread safe?
For example, we have a static ThreadLocal field and a setter:
private static final ThreadLocal threadLocalField = new ThreadLocal; public static void getSXTransaction() { threadLocalField.set(new MyValue()); }
I want to know, because Java There is no implicit synchronization in lang. ThreadLocal #set method, so what is the guarantee of thread safety? I know that the treadlocal class is completely thread safe in nature, but I can't understand how it is implemented
This is its source code:
/** * Sets the current thread's copy of this thread-local variable * to the specified value. Most subclasses will have no need to * override this method,relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current thread's copy of * this thread-local. */ public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this,value); else createMap(t,value); }
Solution
This is safe because getmap returns the mapping for a given (i.e. current) thread No other thread can mess this up So it really depends on the implementation of getmap to ensure that any thread can - and as far as I know, it is only delegated to a field in the thread object I don't know if getmap has ever passed any threads other than the current thread - if so, it may be a bit tricky - but I suspect they have been carefully written to ensure that they are not a problem:)