Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with static field and singleton

Tags:

java

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 (actually, in another singleton-class constructor) I use something like this:

private final Singleton singleton=Someclass.getSingleton();

my singleton always null

Question Why?

like image 654
Dmitry Zaytsev Avatar asked Jan 24 '12 12:01

Dmitry Zaytsev


2 Answers

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.

like image 81
axtavt Avatar answered Oct 21 '22 23:10

axtavt


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;
  }
}
like image 24
tobiasbayer Avatar answered Oct 21 '22 23:10

tobiasbayer