Volatile with synchronized together

java, multithreading

Solution

The purpose of this example is to point out that `syncronized` without `volatile` isn't enough in this case given the fact that object can be published unsafely (i.e. without `volatile` in `Foo`):

If the helper field in the Foo class is not declared volatile, the n field should be declared volatile so that a happens-before relationship is established between the initialization of n and the write of Helper to the helper field. This is in compliance with guideline “VNA06-J. Do not assume that declaring an object reference volatile guarantees visibility of its members” on page 35. This is required only when the caller (class Foo) cannot be trusted to declare helper volatile.

That's correct, but they chose a bad example to demonstrate it, because `volatile` without syncrhonization is enough in this case.

Problem

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?

Original source