ThreadLocal 上的操作是否必须同步? [英] Do operations on ThreadLocal have to be synchronized?

查看:82
本文介绍了ThreadLocal 上的操作是否必须同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我偶然发现的代码:

Here is the code I've stumbled across:

class TransactionContextHolder {

private static final ThreadLocal<TransactionContext> currentTransactionContext = new NamedInheritableThreadLocal<TransactionContext>(
    "Test Transaction Context");


static TransactionContext getCurrentTransactionContext() {
    return currentTransactionContext.get();
}

static void setCurrentTransactionContext(TransactionContext transactionContext) {
    currentTransactionContext.set(transactionContext);
}

static TransactionContext removeCurrentTransactionContext() {
    synchronized (currentTransactionContext) {
        TransactionContext transactionContext = currentTransactionContext.get();
        currentTransactionContext.remove();
        return transactionContext;
    }
}

}

currentTransactionContext 字段的类型为 ThreadLocal,它是该类中唯一的字段.

The currentTransactionContext field is of type ThreadLocal and it is the only field in the class.

在我看来,这里不需要同步,因为存储在 ThreadLocal 中的值与特定线程相关联,因此它不是共享状态.此外,我认为它会影响性能,因为 currentTransactionContext 本身是共享的,并且只允许一个线程进入块,而许多线程可以并行执行而不影响正确性.

It seems to me that synchronization is not needed here because value stored in ThreadLocal is associated with particular thread and thus it's not a shared state. In addition I think it impacts performance as currentTransactionContext itself is shared and only one thread is allowed to enter the block while many can do it in parallel without impacting correctness.

这里需要同步吗?

推荐答案

一般来说,很难对线程安全做出保证,因为线程安全是程序的一个属性.整个程序,并且 synchronized 可以协调程序的许多不同部分的行为.

In general, it's hard to make guarantees about threadsafety given only a tiny snippet of a program, since threadsafety is a property of the whole program, and synchronized can coordinate behavior across many different parts of a program.

例如:也许其他地方还有其他一些代码使用疯狂的不安全反射来尝试检查和/或改变 ThreadLocal 的内部结构,因此如果您在不锁定的情况下改变 ThreadLocal 会中断?

For example: maybe there's some other piece of code somewhere else that uses crazy unsafe reflection to try to inspect and/or mutate the guts of the ThreadLocal, and that will therefore break if you mutate the ThreadLocal without locking?

但实际上,您是对的:没有任何理由在 ThreadLocal 实例上进行同步,除非在其 initialValue 方法内部进行同步.ThreadLocal 本身就是一种线程安全机制,它管理其线程安全性比通过附加 synchronized 无论如何都要好.

Realistically, though, you are quite right: there's never any reason to synchronize on a ThreadLocal instance, except perhaps inside its initialValue method. ThreadLocal is itself a threadsafety mechanism, and it manages its threadsafety better than you could get by tacking on synchronized anyway.

(Margaret Bloom 的帽子提示,用于指出 initialValue 案例.)

(Hat-tip to Margaret Bloom for pointing out the initialValue case.)

这篇关于ThreadLocal 上的操作是否必须同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆