I have this singleton class

public final class MySingleton{
    public static MySingleton singletonInstance;

    private MySingleton(){}

    static{
       singletonInstance=new MySingleton();
    }

    public static MySingleton getInstance(){
       return singletonInstance;
    }

}

I wanted to know is there any other simpler and better way of creating a singleton instance?

Recommended Answers

All 4 Replies

Two more ways of doing it:

Holder idiom is normally used when you need lazy initialization. Enum approach is used to cut down on the line count and is good if you don't want lazy initialization and error handling when creating singleton instances.

the most used way (in code that I've seen so far) is a bit different. also, I would keep the instance as a private variable.

public class MySingleton{
  private static MySingleton instance = null;

  private MySingleton(){

  }

  public static MySingleton getInstance(){
    if ( instance == null )
      instance = new MySingleton();
    return instance;
  }
}

Yes, keeping the variable private is a good idea, but stultuske's version is not thread safe, whereas the original version and the enum version are both thread safe.

well... personally haven't worked much on applications that required Singletons, and was only talking about those :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.