. .
A modern approach to creating an object in thread safe mode uses the AtomicReference compareAndSet in a loop, as described in Goetz Java Concurrency in action (chapter 15). This does not block your threads and provides much greater performance than a synchronized block.
private final AtomicReference<SomeObject> someObject = new AtomicReference<>();
void buildIt() {
SomeObject obj = new SomeObject();
SomeObject current = someObject.get();
while (true) {
if (someObject.compareAndSet(current, obj))
break;
}
}
source
share