replace the following code snippets:
private void loadFactory() {
...
myFactory = factory;
}
private MyFactory myFactory;
public MyFactory getMyFactory() {
return myFactory;
}
with:
private void loadFactory() {
...
myFactoryRef.set(factory);
}
private AtomicReference<MyFactory> myFactoryRef;
public MyFactory getMyFactory() {
return myFactoryRef.get();
}
and you do not need to bother with any additional synchronization.
The atomic reference ensures that updates to the variable are atomic.
So other threads calling getMyFactory()
will either see the old instance or the new instance of MyFactory
and no additional synchronization will be required in loadFactory()
or refreshMyFactory()
.