Declaring an object as volatile

后端 未结 4 1264
有刺的猬
有刺的猬 2021-02-05 15:33

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 v

4条回答
  •  醉梦人生
    2021-02-05 16:00

    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';
    }
    

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

    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.

提交回复
热议问题