java - volatile keyword also for non-primitives

java, volatile

Solution

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.

Problem

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.

Original source