سؤال

I have a queston regarding double-checked locking. Consider this example:

public class Singleton {

     private static volatile Singleton instance = null;

     public static Singleton getInstance() {
        if(instance  == null) {
            synchronized(Singleton.class) {
                if(instance  == null) {
                    instance  = new Singleton();
                }
            }
        }
        return instance ;
    }
}

As I have understood, the above code is the correct way to make a Singleton class.

However, NetBeans wants me to remove the outer if statement, so it would look like this:

public class Singleton {

     private static volatile Singleton instance = null;

     public static Singleton getInstance() {
        synchronized(Singleton.class) {
            if(instance  == null) {
                instance  = new Singleton();
            }
        }
        return instance ;
    }
}

The only differece between these two snippets is that in the second example, the code will always get into the synchronized block and in the first it will not. Why would I listen to NetBeans and remove the outer if statement? It should be better avoid the locking.

هل كانت مفيدة؟

المحلول

NetBeans's automatic hint system obviously isn't aware that it's possible to do double-checked locking correctly with volatile, as you've done, so it suggests full locking instead. Better safe than sorry. But you're right in this case, not NetBeans.

نصائح أخرى

Most of the time, the singleton will be used, and doesn't cost much to create, so just make it simple:

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

    public static Singleton getInstance() {
        return INSTANCE;
    }
    ...
}

If you really want lazy instantiation, use a static inner class:

public class Singleton {
    public static Singleton getInstance() {
        return Holder.INSTANCE;
    }
    ...

    private static class Holder {
        private static final Singleton INSTANCE = new Singleton();
    }
}

Don't listen to NetBeans in this situation. Your first code sample is correct.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top