Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton using AtomicReference

Tags:

java

singleton

Is it correct implementation of lazy-initializing singleton using AtomicReference? If no - what are the possible issues?

import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicReference;

public class Singleton implements Serializable {

    private static final Singleton _instance = new Singleton();

    private static AtomicReference<Singleton> instance = new AtomicReference<Singleton>();

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance.compareAndSet(null, _instance)) {
            synchronized (_instance) {
                _instance.init();
                instance.set(_instance);
            }
        }
        return instance.get();
    }

    private void init() {
        // do initialization
    }

    private Object readResolve() throws ObjectStreamException {
        return getInstance();
    }

}
like image 825
jdevelop Avatar asked May 09 '11 14:05

jdevelop


2 Answers

No, this is bad:

public static Singleton getInstance() {
    // new "singleton" for every method call
    Singleton s = new Singleton();
                   ^^^^^^^^^^^^^^
    if (instance.compareAndSet(null, s)) {
        synchronized (s) {
            s.init();
        }
    }
    return instance.get();
}

Using an AtomicReference is a nice idea, but it won't work because Java doesn't have lazy evaluation.


The classic post 1.5 singleton methods are:

Eager Singleton:

public final class Singleton{
    private Singleton(){}
    private static final Singleton INSTANCE = new Singleton();
    public Singleton getInstance(){return INSTANCE;}
}

Lazy Singleton with inner holder class:

public final class Singleton{
    private Singleton(){}
    private static class Holder{
        private static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance(){return Holder.INSTANCE;}
}

Enum Singleton:

public enum Singleton{
    INSTANCE;
}

You should probably stick with one of these

like image 140
Sean Patrick Floyd Avatar answered Oct 18 '22 02:10

Sean Patrick Floyd


You've got a race condition, in that you may return an instance of the Singleton before init is called on it. You could wrap singleton if you wanted a once-only init. However, we know how to implement singletons in a simple, efficiently manner and mutable singletons are pure evil..

like image 1
Tom Hawtin - tackline Avatar answered Oct 18 '22 03:10

Tom Hawtin - tackline