gpt4 book ai didi

java - 在静态变量中引用子类

转载 作者:行者123 更新时间:2023-12-02 11:38:22 25 4
gpt4 key购买 nike

Intellij 检查工具警告在静态变量中引用子类不是一个好的做法,因为它可能会导致死锁。使用以下文本:

This inspection reports classes that refer to their own subclasses intheir static initializers or in static fields. Such references cancause JVM-level deadlocks in multithreaded environment, when onethread tries to load superclass and another thread tries to loadsubclass at the same time.

以下示例表明:

class Generator {

public static Generator fiveGenerator = new FixedGenerator(5);

public static Generator sixGenerator = new FixedGenerator(6);

int generateNumber() {
//some generation code
return 1;
}

private static class FixedGenerator
extends Generator {

FixedGenerator(int num) {
this.num = num;
}

@Override
int generateNumber() {
return this.num;
}

private int num;
}
}

请注意:

  • FixedGenerator 类是并且应该是私有(private)的。

  • fourGeneratorsixGenerator 是并且应该是公共(public)的。

对此我有两个问题:

  • 这是一种不好的做法吗?为什么?这怎么会造成死锁呢?

  • 等效代码实现该功能的正确方法是什么?

最佳答案

这段代码不会导致任何死锁。
死锁和并发有关,你没有并发。
可能有初始化问题,但您也不会,因为您没有循环,因为FixedGenerator()调用Generator()Generator() 不会调用 FixedGenerator()

Is it a bad practice?

这是因为类不应该引用/知道它们的子类。

What's the right way to equivalent code implement that?

您可以避免私有(private)类中的继承。
作为替代方案,您可以选择组合而不是继承。

关于java - 在静态变量中引用子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755164/

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