java - ThreadLocal 线程安全吗?

标签 java multithreading thread-safety

例如,我们有一个静态的 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/

相关文章:

java - 更新子文档的所有元素,其中子文档是列表的一部分

java - 寻求在 1.14 Minecraft 中设置粒子的帮助

multithreading - 如何使用 posix 信号量实现屏障?

java - 从另一个线程暂停线程,并从另一个线程停止/启动它

java - 了解 spring-social 中的 SignInAdapter

java - 可嵌入的跨平台 Web 浏览器?

php - 在 PHP 中启动新进程/线程的最简单方法

java - 我想知道为什么这个结果不是1000000

c# - C# 中的线程和 TcpListener

c# - 从另一个表单更新对话框