Initialization lock for singleton I'd like someone to double-check my use of Atomic primitives, because multi-threading is hard.

What I don't want to do is locking the whole get method, or having too many pre-checks per get() call.

private final static AtomicReference&lt;T&gt; REFERENCE = new AtomicReference&lt;&gt;();

private final static AtomicBoolean IS_CREATED = new AtomicBoolean(false);

public static MyObject get() {
    if (IS_CREATED.compareAndSet(false, true)) {
        REFERENCE.set(new MyObject());
    }
    return REFERENCE.get();
}
As vnp points out, your code is incorrect because a thread may read REFERENCE after IS_CREATED is set but before REFERENCE is set. Here are a couple alternatives:


use double-checked locking:

private static volatile T reference;
public static T get() {
    if (reference == null)
        synchronized(ThisClass.class) {
            if (reference == null)
                reference = new MyObject();
        }
    return reference;
}

use static class initialization:

private static class Lazy {
    private static final T reference = new MyObject();
}
public static T get() {
    return Lazy.reference;
}

use optimistic creation with CAS (this might create multiple instances but only one instance will be returned):

private static final AtomicReference&lt;T&gt; reference = new AtomicReference&lt;&gt;();
public static T get() {
    if (reference.get() == null)
        reference.compareAndSet(null, new MyObject());
    return reference.get();
}