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.
Rox
source share