Java – singleton using atomicreference
•
Java
Is the deferred initialization singleton correctly implemented using atomicreference? If not – what are the possible problems?
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();
}
}
Solution
No, it's 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();
}
public final class Singleton{
private Singleton(){}
private static final Singleton INSTANCE = new Singleton();
public Singleton getInstance(){return INSTANCE;}
}
public final class Singleton{
private Singleton(){}
private static class Holder{
private static final Singleton INSTANCE = new Singleton();
}
public Singleton getInstance(){return Holder.INSTANCE;}
}
public enum Singleton{
INSTANCE;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
