1

Please refer below code and help me to understand why this not a valid singleton implementation.

class A{
    private static A ob;

    private A(){}
    static {
        ob = new A();
    }
    public static A getInstance() {
        return ob;
    }
}
  • 2
    you need to hide the empty costructor with `private A() {}` – SomeJavaGuy Oct 07 '15 at 13:05
  • 2
    You can drop the static initializer block and just declare it as `private static final A ob = new A();`, it is semantically identical. – Andy Turner Oct 07 '15 at 13:06
  • @AndyTurner But declaring a `static` brackets will make the code execute even if he never requires an instance of A, won't it? – user2651804 Oct 07 '15 at 13:09
  • 2
    @user2651804 it is semantically identical. Try compiling it with the static initializer and with a field initializer, the resulting bytecode is the same. The field initializer *becomes* a static initializer, it's just less verbose. – Andy Turner Oct 07 '15 at 13:09
  • Thanks friends for your responses, I forget to add private constructor. Please let me know if updated code still required any changes for a valid singleton example – Masarrat Siddiqui Oct 08 '15 at 13:59
  • @AndyTurner: I think it would not be semantically identical. Putting the code in a static block will make it thread-safe as it will be guaranteed to be executed only once. Please correct me if I am wrong. – displayName Jun 14 '18 at 20:14
  • @displayName have you tried compiling the two versions and comparing the bytecode, as suggested in my previous comment? – Andy Turner Jun 14 '18 at 20:16

2 Answers2

4

It is not a valid singleton (multiple instances may be instantiated) because you get the default constructor. Add a private constructor (which will prevent the default constructor from being inserted). And you probably want to override clone().

private A() {
}

@Override
public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException(this.getClass().getName() 
            + ": is a singleton.");
}

I would usually use an enum to implement a singleton.

Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

Nothing stops me creating a new instance of A by calling new A(), so I can have multiple instances of it.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243