Is there any reason to use volatile and synchronized together in this code?
public class Helper {
private volatile int n;
private final Object lock = new Object();
public Helper(int n) {
this.n = n;
}
public void setN(int value) {
synchronized (lock) {
n = value;
}
}
}
Class Helper must be thread safe. I’ve got this example from the “Java Concurrency Guidelines” book, but it is still not clear: what is the reason for using volatile and synchronized together in this example?
The purpose of this example is to point out that
syncronizedwithoutvolatileisn’t enough in this case given the fact that object can be published unsafely (i.e. withoutvolatileinFoo):That’s correct, but they chose a bad example to demonstrate it, because
volatilewithout syncrhonization is enough in this case.