Problem with static field and singleton

I have two classes:

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

and

 public class Someclass{ private static final Singleton singleton=Singleton.getInstance(); public static Singleton getSingleton(){ return singleton; } } 

Problem

If somewhere (in fact, in another constructor of a singleton class), I use something like this:

 private final Singleton singleton=Someclass.getSingleton(); 

my singleton always null

Question Why?

+7
source share
2 answers

Your example works fine, so it is not complete.

Perhaps in your real application you have a dependecy loop between your classes, so getSingleton() is called before Someclass initialization is Someclass , something like the following, but with a few classes involved:

 public class Foo { private static Foo INSTANCE = new Foo(); // Prints null private static String s = "foo"; public Foo() { System.out.println(s); } } 

This is especially likely if you have several interdependent singleons implemented this way. Try to find and eliminate these cycles.

Also, it might be better to use some kind of DI or Service Locator pattern instead of manually executing singleton behavior.

+8
source

You should create a singleton instance the first time getInstance() called, not statically. This will work regardless of dependency cycles.

 public class Singleton { private static Singleton instance = null; private Singleton(){...} public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } } 
+1
source

All Articles