Suppose the following singleton:
public class Test{
private static volatile Test test = null;
private static int test_int = 0;
private static String test_string = "test";
public int getInt(){
return test_int;
}
public String getString(){
return test_string;
}
private static Test getInstance(){
if(test == null){
synchronized(Test.class){
if(test == null)
test = new Test();
}
}
}
By declaring the singleton instance Test to be volatile are test_int and test_string also considered to be volatile or must they be declared as such? I want to think that by making the class itself Volatile then everything under that class would be volatile as well … however I am not sure about this. Thanks ahead of time.
No, they aren’t considered to be volatile. Only the
testvariable is volatile. After the value oftesthas been obtained (viagetInstance) its volatility is irrelevant to the rest of the client’s behaviour.Personally I would consider using
AtomicIntegerandAtomicReferenceinstead ofvolatile, to be honest. I don’t know about anyone else, but I find volatile behaviour hard to reason about reliably.Note that your probably don’t want your
test_intandtest_stringvariables to be static…