有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的线程本地初始化?

我正在构建一个以ThreadLocal作为实例变量的singleton,这个singleton有一个可以被多个线程访问的方法,它是惰性实例化的。现在我在想这样的事情:

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

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

所以问题是,初始化这个类变量的最佳位置是哪里,还是应该是一个类变量


共 (2) 个答案

  1. # 1 楼答案

    可以保证以线程安全的方式执行静态初始值设定项。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).

  2. # 2 楼答案

    使用Lamda,我们可以这样写:

    private ThreadLocal<Map<String,String>> bindingContext = ThreadLocal.withInitial(HashMap::new);