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;
    }
}
7
  • 2
    you need to hide the empty costructor with private A() {} Commented Oct 7, 2015 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. Commented Oct 7, 2015 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? Commented Oct 7, 2015 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. Commented Oct 7, 2015 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 Commented Oct 8, 2015 at 13:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Elliott, but why there is a need for clone method? i never implements cloneable
What happens if someone clones a Singleton?
3

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

1 Comment

I Agree Andy, added private constructor, Please review and let me know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.