Chr*_*ncy 2 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过声明单例实例Test是volatile,test_int和test_string也被认为是volatile,或者它们是否必须声明为?我想通过使类本身具有Volatile,那么该类下的所有东西都会变得不稳定......但是我不确定这一点.提前谢谢.
不,他们不被认为是不稳定的.只有该test变量波动.在test获得(通过getInstance)价值之后,其波动性与客户的其他行为无关.
就个人而言,我会考虑使用AtomicInteger而AtomicReference不是volatile说实话.我不知道其他任何人,但我发现挥发性行为难以可靠地推理.
请注意,您可能不希望你test_int和test_string变量是静态的...
| 归档时间: |
|
| 查看次数: |
791 次 |
| 最近记录: |