In fact, you do not need atomic logic code with the following code:
public class YourClass() {
volatile boolean initialized = false;
public void ensureInitialized() {
if ( initialized ) return;
synchronized(this) {
if (!initialized) {
initialize();
initialized = true;
}
}
}
public void initialize() { ... };
}
Since the initialization code will only be called once, there is no real benefit from using AtomicBoolean.
Syncing to 'this' may take a little longer, but it also creates an AtomicBoolean. Both operations are performed only once.
Overall, this solution uses less memory.
EDIT: Updated Solution
source
share