例如,我们有一个静态的 ThreadLocal 字段和一个 setter:
private static final ThreadLocal threadLocalField = new ThreadLocal;
public static void getSXTransaction() {
threadLocalField.set(new MyValue());
}
我想知道,由于 java.lang.ThreadLocal#set 方法中没有隐式同步,这里的线程安全保证是什么? 我知道 TreadLocal 类本质上是完全线程安全的,但我不明白它是如何实现的。
这是它的源代码:
/**
* 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);
}
最佳答案
这是安全的因为getMap
返回给定(即当前)线程的映射。没有其他线程会搞乱它。所以这真的取决于 getMap
的实现确保 that's 对任何线程都适用 - 据我所知,它只是委托(delegate)给 Thread
中的一个字段目的。我不清楚是否 getMap
other 一直传递当前线程以外的任何线程 - 如果是,那可能会很棘手 - 但我怀疑它都经过仔细编写以确保这不是问题:)
关于java - ThreadLocal 线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27188279/