Java - volatile reference to mutable object - will updates to the object's fields be visible to all threads

Mr_and_Mrs_D picture Mr_and_Mrs_D · May 25, 2014 · Viewed 8.5k times · Source

... without additional synchronization ? The Tree class below is meant to be accessed by multiple threads (it is a singleton but not implemented via an enum)

class Tree {

    private volatile Node root;

    Tree() {
        root = new Node();
        // the threads are spawned _after_ the tree is constructed
    }

    private final class Node {
        short numOfKeys;
    }
}
  • Will updates to the numOfKeys field be visible to reader threads without any explicit synchronization (notice that both readers and writers have to acquire an instance of ReentrantReadWriteLock - same instance for each node - but barring that) ? If not would making numOfKeys volatile suffice ?
  • Is changing the root as simple as root = new Node() (only a writer thread would change the root, apart from the main thread which calls the Tree constructor)

Related:

EDIT: interested in post Java 5 semantics

Answer

SLaks picture SLaks · May 25, 2014

No.

Placing a reference to an object in a volatile field does not affect the object itself in any way.

Once you load the reference to the object from the volatile field, you have an object no different from any other object, and the volatility has no further effect.