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 (actually, in another singleton-class constructor) I use something like this:
private final Singleton singleton=Someclass.getSingleton();
my singleton always null
Question Why?
Your example works fine, thus it’s incomplete.
Perhaps in your real application you have a dependecy cycle between your classes, so that
getSingleton()is invoked before initialization ofSomeclassis completed, something like the following, but with multiple classes involved:It’s especially likely if you have multiple interdependent singletons implemented this way.
Try to find and elmininate these cycles.
Also, perhaps it would be better to use some kind of DI or Service Locator pattern instead of implementing singleton behaviour manually.