gpt4 book ai didi

java - 在完全初始化(由另一个线程)之前(在一个线程中)使用的类?

转载 作者:搜寻专家 更新时间:2023-11-01 00:55:28 24 4
gpt4 key购买 nike

在我使用的库的深处,有两个相互引用的类 — 称它们为 MR1MR2 — 这样 MR1.<clinit>原因MR2被加载类和MR2.<clinit>原因MR1进行类加载。

图书馆还有一个Util引用 MR1 的类, 这样 Util.<clinit>原因MR1进行类加载。

最后,它有一个顶级类——称之为 TopLevel — 其构造函数具有如下代码:

Util.callStaticUtilMethod();
MR2.callStaticMR2Method();

所以整体的依赖图是这样的:

dependency graph

我最近遇到了一个类加载器死锁,其中两个线程恰好都在实例化 TopLevel同时,还没有加载这些其他类。一个线程卡在 MR1.<clinit> 中, 里面 Util.<clinit> ,准备打电话Util.callStaticUtilMethod() ;另一个成功通过Util.callStaticUtilMethod() , 并陷入 MR2.<clinit> ,准备打电话MR2.callStaticMR2Method() . (然后一堆其他线程卡在了 MR2.callStaticMR2Method() 行。)

我不明白的是 — 如果一个线程仍然卡住、死锁,在 Util.<clinit> 中,那么所有其他线程如何能够通过 Util.callStaticUtilMethod()称呼?一个类在完全初始化之前是否应该可以使用?如果是这样,那么这能走多远?例如,一个静态 final 字段是否可以在一个线程被另一个线程初始化之前访问它? (从其他线程无法通过 MR2.callStaticMR2Method() 调用这一事实来看,幸运的是,这似乎不是完全免费;但我不能说出规则可能是什么。)

最佳答案

JLS ( §12.4.1 ) 指出静态方法调用将触发初始化:

A class or interface type T will be initialized immediately before ... a static method declared by T is invoked.

它继续 ( §12.4.2 ) 描述当线程触发初始化时应该发生什么:

If ... initialization is in progress for C by some other thread, then ... block the current thread until informed that the in-progress initialization has completed.... Otherwise, record the fact that initialization of the Class object for C is in progress by the current thread.... If the execution of the initializers completes normally ... label the Class object for C as fully initialized, [and] notify all waiting threads.

所以理论上你所描述的是不可能的。然而,有这个有点模糊的脚注:

Compile-time analysis may, in some cases, be able to eliminate many of the checks that a type has been initialized from the generated code.... Such analysis must, however, fully account for concurrency and for the fact that initialization code is unrestricted.

按照我的解释,这可以授予编译器避免阻塞不依赖于任何仍在初始化状态或以其他方式影响内存模型的静态方法调用的自由。

就是说,我试图复制行为(静态方法在其类的初始化程序之前返回),但没能做到。您不应该排除您只是误读了日志的可能性。

关于java - 在完全初始化(由另一个线程)之前(在一个线程中)使用的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512265/

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