... 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;
}
}
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 ?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
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.