0

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?

4
Contributors
4
Replies
6
Views
4 Years
Discussion Span
Last Post by stultuske
0

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

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.

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.