Dmitry Zaytsev
Dmitry Zaytsev

Reputation: 23962

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

private final Singleton singleton=Someclass.getSingleton();

my singleton always null

Question Why?

Upvotes: 7

Views: 1013

Answers (2)

tobiasbayer
tobiasbayer

Reputation: 10379

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;
  }
}

Upvotes: 1

axtavt
axtavt

Reputation: 242696

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.

Upvotes: 8

Related Questions