How to achieve this with AtomicBoolean?

How to make sure that the initialize () method is called only once? The following is an unsafe version of a thread that I would like to reorganize to use AtomicBoolean. All I want is that initialize () is called only once

if (!initialized) 
{
   initialize();
   initialized = true;
}
+3
source share
3 answers
private final AtomicBoolean initialized = new AtomicBoolean(false);


//in some method:

if(!initialized.getAndSet(true))
{
    initialize();
}
+4
source

An atomic logical value will not be enough for you, because the second thread entering the code block will drop, even if initialization has not yet been completed. Try this, which will block a second, in parallel, only if the first has not yet completed, and will be very fast when performing initialization:

volatile boolean initialized = false;

private final Object LOCK = new Object();

public void ensureInitialized() {
    if( !initialized ) {
        synchronized(LOCK) {
            if( !initialized ) {
                initialize();
                initialized = true;
            }
        }    
    }
}

, .

+3

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

    }

    // The code of this method could be moved
    // into the synchronized statement above
    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

0
source

All Articles