For example, we have a static ThreadLocal field an a setter:
private static final ThreadLocal threadLocalField = new ThreadLocal;
public static void getSXTransaction() {
threadLocalField.set(new MyValue());
}
I wonder, what are the guarantees of thread safety here as there is no implicit synchronization in the java.lang.ThreadLocal#set method? I know it makes sense for the TreadLocal class to be fully thread safe by it's nature but I cannot understand how it's being accomplished.
Here is the source code for it:
/**
* 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);
}