Should I synchronize a static volatile variable?
java, thread-safety, volatile
Solution
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:
Initialize on class load (knowing that that will be lazy, but not as lazy as waiting until `getMyObj` is first called):
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();
}
Problem
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; } ``` 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? To put it another way: does volatile get you around having to synchronize access to writes on a static variable?