我应该同步静态volatile变量吗? [英] Should I synchronize a static volatile variable?
问题描述
关于这个问题有几个问题,但大多数问题围绕这个问题,因为这不是问题的意图。
There are a few questions on this subject, but most skirt around this issue because it's not the intent of the question.
如果我班上有静态不稳定因素:
If I have a static volatile in my class:
private static volatile MyObj obj = null;
以及我在下面的方法中:
and in a method below I do:
public MyObj getMyObj() {
if (obj == null) {
obj = new MyObj();// costly initialisation
}
return obj;
}
我需要同步以确保只有一个线程写入字段,或者任何写入是否会立即显示给评估 obj == null
条件的其他线程?
will I need to synchronize to ensure only one thread writes to the field, or will any writes be immediately visible to other threads evaluating the obj == null
conditional?
换句话说:volatile会让你不得不同步访问静态变量上的写入吗?
To put it another way: does volatile get you around having to synchronize access to writes on a static variable?
推荐答案
你肯定需要一些类锁定,以确保只有一个线程写入字段。无论波动性如何,两个线程都可以看到 obj
为空,然后两者都开始用当前代码初始化。
You'd definitely need some sort of locking to ensure that only one thread writes to the field. Regardless of the volatility, two threads can both "see" that obj
is null, and then both start initializing with your current code.
就个人而言,我会选择以下三个选项之一:
Personally I'd take one of three options:
-
在类加载时初始化(知道这将是懒惰,但不像在第一次调用
getMyObj
之前一样懒惰:
private static final MyObj obj = new MyObj();
使用无条件锁定:
Use unconditional locking:
private static MyObj obj;
private static final Object objLock = new Object();
public static MyObj getMyObj() {
synchronized(objLock) {
if (obj == null) {
obj = new MyObj();
}
return obj;
}
}
使用嵌套类进行懒惰:
Use a nested class for laziness that way:
public static MyObj getMyObj() {
return MyObjHolder.obj;
}
private static class MyObjHolder {
static final MyObj obj = new MyObj();
}
这篇关于我应该同步静态volatile变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!