Suppose that multiple threads use a same Configuration object, sometimes reading a truly immutable object from it. Additionally, the reference to the immutable object could get updated.
public class Configuration {
private ImmutableObject immutableObject;
private ReentrantReadWriteLock lock;
private void update() {
lock.writeLock().lock();
immutableObject = getNewImmutableObject();
lock.writeLock().unlock();
}
public ImmutableObject getImmutableObject() {
ImmutableObject newRef;
lock.readLock().lock();
newRef = immutableObject;
lock.readLock().unlock();
return newRef;
}
}
Is this a good way to make the access of immutableObject thread-safe? I think I don't even need the lock, because the update of the reference is atomic, but I'm not sure.