Pattern pour instanciation singleton paresseux thread-safe en Java

le paresseux thread-safe singleton instantion est un peu pas facile à comprendre pour chaque codeur, j'ai donc voulu créer une classe dans notre entreprise, cadre pour faire le travail.

Qu'en pensez-vous? Voyez-vous quelque chose de mauvais? Est-il quelque chose de similaire, comme dans Apache Commons? Comment puis-je faire mieux?

Supplier.java

public interface Supplier<T> {
    public T get();
}

LazyThreadSafeInstantiator.java

public class LazyThreadSafeInstantiator<T> implements Supplier<T> {
    private final Supplier<T> instanceSupplier;

    private volatile T obj;

    public LazyThreadSafeInstantiator(Supplier<T> instanceSupplier) {
        this.instanceSupplier = instanceSupplier;
    }

    @Override
    //http://en.wikipedia.org/wiki/Double-checked_locking
    public T get() {
        T result = obj;  //Wikipedia: Note the usage of the local variable result which seems unnecessary. For some versions of the Java VM, it will make the code 25% faster and for others, it won't hurt.
        if (result == null) {
            synchronized(this) {
                result = obj;
                if (result == null) {
                    result = instanceSupplier.get();
                    obj = result;
                }
            }
        }
        return result;
    }
}

Exemple d'utilisation:

public class Singleton1 {
    private static final Supplier<Singleton1> instanceHolder =
        new LazyThreadSafeInstantiator<Singleton1>(new Supplier<Singleton1>() {
            @Override
            public Singleton1 get() {
                return new Singleton1();
            }
        });

    public Singleton1 instance() {
        return instanceHolder.get();
    }

    private Singleton1() {
        System.out.println("Singleton1 instantiated");
    }
}

Grâce

source d'informationauteur Igor Mukhin