java - 多线程声明期间静态变量初始化

标签 java multithreading static-variables

我想将以下代码添加到我的类中:

static private final ILogic_P logicInstanceI =
    (ILogic_P)Factory.CreateAnon("some.path.ILogic_P" + (SomeClass.isIMDB() ? "1" : "2"));

public static ILogic_P getLogicInstanceI(){
    return logicInstanceI;
}

我不知道静态变量的初始化是否是线程安全的。 两个线程是否有可能同时尝试初始化此属性?

最佳答案

答案由 Java Language Specification §12.4.2 给出:

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. […]

注意最后一句以“Java 虚拟机的实现负责照顾 ...”开头

因此,在类初始化的情况下,您不负责同步,并且为 static 变量分配初始值是类初始化的一部分,如 §8.3.2 中所指定。 :

8.3.2. Field Initialization

If a declarator in a field declaration has a variable initializer, then the declarator has the semantics of an assignment (§15.26) to the declared variable.

If the declarator is for a class variable (that is, a static field), then the following rules apply to its initializer:

  • At run time, the initializer is evaluated and the assignment performed exactly once, when the class is initialized (§12.4.2).

关于java - 多线程声明期间静态变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34182650/

相关文章:

java - 了解 PriorityQueue 比较器

java - 如果一个线程打开一个套接字并且主程序退出会发生什么?

java - 使用静态成员变量并行化类

c# - 将集合返回为只读

java - 如何让多个线程绘制到 AWT 组件上?

java - 在多线程情况下延迟初始化静态变量

java - 我们如何将可调用对象转换为可运行对象

java - 使用 JAXB 将 XML 标记内容存储到不同的变量

python - Python 中的静态类变量——列表和对象

c++ - 在 C++ 中,如果两个不同的函数声明同一个静态变量会怎样?