创建volatile类是否保证volatile类变量

时间:2011-03-06 18:31:53

标签: java singleton volatile

假设以下单身:

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();
             }
         }
    }

通过声明单例实例Test是volatile,test_int和test_string也被认为是volatile或者必须声明它们吗?我想通过使类本身具有Volatile,那么该类下的所有东西都会变得不稳定......但是我不确定这一点。提前谢谢。

1 个答案:

答案 0 :(得分:9)

不,他们不被认为是不稳定的。 test变量是易失性的。获得test的价值后(通过getInstance),其波动性与客户的其他行为无关。

说实话,我个人会考虑使用AtomicIntegerAtomicReference代替volatile。我不知道其他任何人,但我发现挥发性行为难以可靠地推理。

请注意,您可能不希望test_inttest_string变量是静态的...