ioz*_*zee 6 java multithreading thread-safety
例如,我们有一个静态ThreadLocal字段和一个setter:
private static final ThreadLocal threadLocalField = new ThreadLocal;
public static void getSXTransaction() {
threadLocalField.set(new MyValue());
}
Run Code Online (Sandbox Code Playgroud)
我想知道,由于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);
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 15
它是安全的,因为getMap返回给定(即当前)线程的映射.没有其他线程可以搞乱这一点.所以,它是真正下到实施getMap,以确保这是正常的任何话题-而据我所看到的,只是委托给中的一个字段Thread对象.这是我不清楚是否getMap是有史以来传递任何线程其他比当前线程-如果是这样,这可能是潜在的麻烦-但我怀疑这一切都经过精心编写的,以确保这不是一个问题:)