例如,我们有一个静态的ThreadLocal字段和一个setter方法:
我想知道这里的线程安全性保证是什么,因为在java.lang.ThreadLocal#set方法中没有隐式同步。我知道ThreadLocal类天生具有完全的线程安全性,但我不明白它是如何实现的。
以下是该方法的源代码:
private static final ThreadLocal threadLocalField = new ThreadLocal;
public static void getSXTransaction() {
threadLocalField.set(new MyValue());
}
我想知道这里的线程安全性保证是什么,因为在java.lang.ThreadLocal#set方法中没有隐式同步。我知道ThreadLocal类天生具有完全的线程安全性,但我不明白它是如何实现的。
以下是该方法的源代码:
/**
* 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);
}