I have a question about the volatile statement in Java. Please look at this constructed example:
class Master {
// Foo is a class with thread-safe methods
public volatile Foo foo;
}
class Worker1 implements Runnable {
protected Master master
void run() { ... };
}
class Worker2 implements Runnable {
protected Master master
void run() { ... };
}
We have 2 worker threads which hold a reference to an object of class Master running at the same time. During their work, both have to access methods of master.foo. At some point, the Foo object of master will be changed by one of the worker threads. Now my question: Does the use of volatile make the whole construction thread-safe? I am asking this because in a Java tutorial from Oracle it says
However, there are actions you can specify that are atomic:
- Reads and writes are atomic for reference variables […]
Atomic actions cannot be interleaved, so they can be used without fear of thread interference.
I just would like to make sure that I understood this correctly.
Thanks in advance 🙂
Reads and writes of references are always atomic in Java, so there is no danger of, for example, seeing the reference in some half-updated state. If this is what you mean by “thread safe” then the operation is thread safe with or without the keyword.
But
volatileis not about atomicity, it affects whether threads can cache writes locally.volatilewould force writes to be written back to main memory and be visible to other threads. If that is what you mean by thread-safe, then yes you need this keyword.volatileitself does not affect whether method calls onfooexclude other threads or not. If that’s what you mean you want to usesynchronized, and in a different place.