Double check locking, does NetBeans bother me?

I have a double check lock question. 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 understand it, the above code is the correct way to create a Singleton class.

However, NetBeans wants me to delete the external if statement, so it will 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 difference between the two fragments is that in the second example, the code will always fall into the synchronized block, and in the first it will not. Why should I listen to NetBeans and delete the external if statement? Better to avoid blocking.

+7
source share
3 answers

NetBeans’s automated prompting system obviously doesn’t know that using volatile you can do a double-check lock since you did this, so a full lock is suggested instead. God saves man, who save himself. But you are right in this case, not NetBeans.

+3
source

In most cases, a singleton will be used and it is not worth creating a lot, so just make it simple:

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

If you really need a lazy instance, 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(); } } 
+3
source

Do not listen to NetBeans in this situation. Your first code example is correct.

0
source

All Articles