Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - volatile keyword also for non-primitives

Tags:

java

volatile

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.

like image 918
John T. Avatar asked May 15 '12 20:05

John T.


People also ask

What is true for volatile keyword in Java?

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.

What is the volatile keyword useful for?

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.

What is volatile and non-volatile in Java?

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.

What is non-volatile in Java?

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.


1 Answers

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.

like image 70
Michael Borgwardt Avatar answered Oct 20 '22 01:10

Michael Borgwardt