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 of Someclass
is completed, something like the following, but with multiple classes involved:
public class Foo {
private static Foo INSTANCE = new Foo(); // Prints null
private static String s = "foo";
public Foo() {
System.out.println(s);
}
}
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.
You should create the singleton instance on the first call to getInstance()
rather than 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With