我有下面的代码。
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);
}
}
我希望在整个多线程应用程序中拥有变量 props
和 pipeline
的单个实例。
我的代码正确还是我遗漏了什么?
谢谢。
最佳答案
可以通过使用方法调用来消除 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/