gpt4 book ai didi

java - Java类是由第一次使用它的线程初始化的吗?

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:13 24 4
gpt4 key购买 nike

让我们假设以下类定义:

public class A {
public final static String SOME_VALUE;

static {
SOME_VALUE = "some.value";
}
}

public class B {
private final String value = A.SOME_VALUE;
}

假设类 A 还没有加载,当类 B 的对象被某个线程 T 实例化时会发生什么?类 A 必须首先加载和实例化。但我的问题是:它是在线程 T 的上下文中完成的,还是在其他一些(特殊的)“类加载器”线程的上下文中完成的?

最佳答案

查看部分 12.4.1 (“初始化发生时”)和 12.4.2 JLS 的(“详细初始化过程”):

The procedure for initializing a class or interface is then as follows:

  1. Synchronize (§14.19) on the Class object that represents the class or interface to be initialized. This involves waiting until the current thread can obtain the lock for that object (§17.1).
  2. If initialization is in progress for the class or interface by some other thread, then wait on this Class object (which temporarily releases the lock). When the current thread awakens from the wait, repeat this step.
  3. If initialization is in progress for the class or interface by the current thread, then this must be a recursive request for initialization. Release the lock on the Class object and complete normally.
  4. If the class or interface has already been initialized, then no further action is required. Release the lock on the Class object and complete normally.
    ...

规范指出初始化发生在当前线程中(意味着任何线程达到导致需要初始化相关类的状态)但 JVM 实现必须做出一些非常严格的同步保证以避免任何问题。

关于java - Java类是由第一次使用它的线程初始化的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2469957/

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