创建 volatile 类是否保证 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 声明为易失性, test_int 和 test_string 也被视为易失性,还是必须如此声明?我想认为,通过使类本身成为易失性的,那么该类下的所有内容也将是易失性的......但是我对此不确定。提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,它们不被认为是不稳定的。 只有
test
变量是易失性的。在获得test
的值(通过getInstance
)后,其波动性与客户端的其余行为无关。老实说,我个人会考虑使用
AtomicInteger
和AtomicReference
而不是volatile
。我不了解其他人,但我发现不稳定的行为很难可靠地推理。请注意,您可能不希望您的
test_int
和test_string
变量是静态的......No, they aren't considered to be volatile. Only the
test
variable is volatile. After the value oftest
has been obtained (viagetInstance
) its volatility is irrelevant to the rest of the client's behaviour.Personally I would consider using
AtomicInteger
andAtomicReference
instead 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_int
andtest_string
variables to be static...