lundi 23 mai 2016

Lazy Singleton what advantages over thread safe one

We had design patterns in school and learned the implementation of a singleton (lazy / not thread safe one) like this:

package com.crunchify.tutorials;
public class CrunchifySingleton {

    private static CrunchifySingleton instance = null;

    protected CrunchifySingleton() {
    }

    // Lazy Initialization (If required then only)
    public static CrunchifySingleton getInstance() {
        if (instance == null) {
            // Thread Safe. Might be costly operation in some case
            synchronized (CrunchifySingleton.class) {
                if (instance == null) {
                    instance = new CrunchifySingleton();
                }
            }
        }
        return instance;
    }
}

Now I found the implementation like this:

package com.crunchify.tutorials;

public class ThreadSafeSingleton {

    private static final Object instance = new Object();

    private ThreadSafeSingleton() {
    }

    // Runtime initialization
    // By defualt ThreadSafe
    public static Object getInstance() {
        return instance;
    }
}

Now I am wondering when the first implementation makes more sense to use, because according to http://ift.tt/1PVWoVQ the second one is thread safe and needs less lines.

Aucun commentaire:

Enregistrer un commentaire