gpt4 book ai didi

java - Java 中的 ThreadLocal 初始化?

转载 作者:行者123 更新时间:2023-11-29 08:06:16 24 4
gpt4 key购买 nike

我正在构建一个将 ThreadLocal 作为实例变量的单例,这个单例有一个可以被多个线程访问的方法,并且它是延迟实例化的。现在我正在考虑这样的事情:

static final ThreadLocal<HashMap> bindingContext = new ThreadLocal<HashMap>();

但我不确定这是否是个好主意,我也可以选择将它设为实例变量,因为我正在使用它(正如我在单例中所说的)。

所以问题是,初始化该类变量的最佳位置在哪里,或者它应该是一个类变量吗?

最佳答案

保证静态初始化器以线程安全的方式执行。 JLS 特别提到了这一点:

Because the Java programming language is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time. There is also the possibility that initialization of a class or interface may be requested recursively as part of the initialization of that class or interface; for example, a variable initializer in class A might invoke a method of an unrelated class B, which might in turn invoke a method of class A. The implementation of the Java virtual machine is responsible for taking care of synchronization and recursive initialization by using the following procedure.


参见 12.4.2 of JLS 部分详细描述了这件事。

编辑:您正在尝试的完全没问题。来自 ThreadLocal 的 javadocs:

ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

关于java - Java 中的 ThreadLocal 初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11002583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com