将对象声明为易失性 [英] Declaring an object as volatile

查看:86
本文介绍了将对象声明为易失性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在Java中将成员变量声明为volatile,这是否意味着所有对象的数据都存储在易失性内存中,或者对对象的引用存储在易失性内存中?

If you declare a member variable as volatile in Java, does this mean that all the object's data is stored in volatile memory, or that the reference to the object is stored in volatile memory?

例如,如果我有以下课程:

For example if I have the following class:

class C{
   int i = 0;
   char c = 'c';
}

如果我声明它的实例如下:

If I declare an instance of it as follows:

private volatile C obj;

是将对obj的引用存储在易失性存储器中,还是将obj的数据(obj.iobj.c)存储在volatile存储器中?

does that store the reference to obj in volatile memory, or obj's data (obj.i and obj.c) in volatile memory?

它是否使obj.cobj.i线程安全?

推荐答案

是的,JVM仅将对象引用视为易失性,而不会将驻留在堆上的对象数据本身视为易失性.如果您要求堆上对象的成员变量是易变的,那么您当然可以将关键字应用于这些基元

Yes only the object reference will be considered to be volatile by the JVM and not the object data itself which will reside on the heap. If you required the member variables of the object on the heap to be volatile you can of course apply the keyword to those primitives

class C {
   volatile int i = 0;
   volatile char c = 'c';
}

重新:您是否要确保变量线程安全的问题取决于您如何使用变量.正如@gerrytan从Oracle文档中指出的那样,volatile关键字确实有助于原子级的读取或写入,但是请注意,这与始终保持线程安全并不相同.考虑以下代码...

Re: your question of whether this makes the variable thread safe, depends on how you are using the variable. As @gerrytan pointed out from the Oracle docs, the volatile keyword does help with a read or write to be atomic, however be warned that this is not the same as it always being thread safe. Consider the following code...

if(obj != null) {
    obj.doSomething();
}

执行空检查的线程仍然有可能在执行obj.doSomething()之前被中断,而另一个线程设置obj = null.这里还需要其他机制,例如synchronized块.

It is still possible that a thread that executes the null check, is interrupted before it executes obj.doSomething(), and another thread sets obj = null. Some other mechanism is required here such as a synchronized block.

这篇关于将对象声明为易失性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆