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;
does that store the reference to obj
in volatile memory, or obj
's data (obj.i
and obj.c
) in volatile
memory?
Does it make obj.c
and obj.i
thread safe or not?
To declare a variable volatile, include the keyword volatile before or after the data type in the variable definition.
The volatile keyword can be used either with primitive type or objects. The volatile keyword does not cache the value of the variable and always read the variable from the main memory. The volatile keyword cannot be used with classes or methods. However, it is used with variables.
Volatile variables have the visibility features of synchronized but not the atomicity features. The values of the volatile variable will never be cached and all writes and reads will be done to and from the main memory.
The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.
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.
private volatile C obj;
That will make only obj
volatile.
Does it make obj.c and obj.i thread safe or not?
No. To make them thread-safe, you have to synchronize the access to them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With