java – ThreadLocal线程安全吗?
发布时间:2020-05-25 01:15:03 所属栏目:Java 来源:互联网
导读:例如,我们有一个静态ThreadLocal字段和一个setter: private static final ThreadLocal threadLocalField = new ThreadLocal;public static void getSXTransaction() { threadLocalField.set(new MyValue());} 我想知道,由于java.lan
|
例如,我们有一个静态ThreadLocal字段和一个setter: private static final ThreadLocal threadLocalField = new ThreadLocal;
public static void getSXTransaction() {
threadLocalField.set(new MyValue());
}
我想知道,由于java.lang.ThreadLocal #set方法中没有隐式同步,所以线程安全的保证是什么? 这是它的源代码: /**
* 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的实现,以确保任何线程都可以 – 并且据我所知,它只是委托给Thread对象中的一个字段.我不清楚getMap是否曾经传递过当前线程以外的任何线程 – 如果是,那可能是有点棘手的 – 但我怀疑它们都是经过仔细编写以确保不是问题:)(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
