I am unsure if the volatile keyword should also be used for non-primitives. I have a class member which is set/assigned by one thread, and accessed by another thread. Should I declare this member volatile?
private /* volatile */ Object o;
public void setMember(Object o) {
this.o = o;
}
public Object getMember() {
return o;
}
Here, setMember(...) is called by one thread and getMember() is called by another one.
If it was a boolean, for example, the answer would be yes.
I am using Java 1.4 and the member in this case is read-only. So I am only caring about visibility in this case, hence my question about the volatile keyword.
For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.
Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem.
The volatile memory stores data and computer programs that the CPU may need in real-time, and it erases them once a user switches off the computer. Cache memory and RAM are types of Volatile memory. Non-volatile memory, on the other hand, is static. It remains in a computer even after a user switches it off.
Non-volatile memory is a very advanced storage technology. It does not use continuous power to keep the data or program files located on the computer so that it becomes an effective power saver. System manufacturers make a variety of non-volatile memory chips for various purposes.
Yes - volatile
has exactly the same significance for reference-type fields that it has for primitive-type fields. Except that in the case of reference types, the members of the object the field refers to must also be designed for multi-threaded access.
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