gpt4 book ai didi

java - 多线程环境中跨整个应用程序的变量的单个实例

转载 作者:行者123 更新时间:2023-12-01 08:56:13 24 4
gpt4 key购买 nike

我有下面的代码。

private static volatile Properties props = null;
private static volatile StanfordCoreNLP pipeline = null;
/**
*
* @return
*/
static {
if (props == null) {
props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
}
if (pipeline == null) {
pipeline = new StanfordCoreNLP(props);
}
}

我希望在整个多线程应用程序中拥有变量 propspipeline 的单个实例

我的代码正确还是我遗漏了什么?

谢谢。

最佳答案

可以通过使用方法调用来消除 volatile ,并通过静态初始化仍然保留线程安全性。

private static final Properties props = initProperties();
private static Properties initProperties() {
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
return props;
}

public static Properties getProperties() {
return props;
}

编辑:不过,为了回答你的问题,是的,你在 OP 中的代码确实是线程安全的,尽管我之前给出的是我个人的做法。

关于java - 多线程环境中跨整个应用程序的变量的单个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42023972/

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