Singleton In Java

 

Singleton design pattern is one of the most used design pattern in software development. Perhaps because its intention is pretty intuitive :

+ Ensure a class only has one instance 

+ Provide a global point of access to it 

When do people use this pattern? Well, when they want ONE unique instance (of a kind) in a system (even with different ways of access). Some examples in software:

+ only one “Find” window displayed for a text editor (regardless of how you open the “Find” : using menu, using shortcut icon, using keyboard Ctrl+F, etc)

+ only one “manager” for the application resources, like one print spooler no matter how much printers are there. Or for logging, for localization (l10n) / internationlization (i18n), for thread pooling, for data caching, …

 

There are at least 8 ways of  Singleton implementations in Java language. My favourite approach is the standard one : lazy initilization .

0/ simple, intuitive, readable (easy to read and understand)

public class JSingleton {

  private static JSingleton instance;

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

  private JSingleton() { //do nothing
  }
}

There are two other variants which are also acceptable:

1/ Use another class to check lazily :

//...
private static SingletonCore instance = null;

  public static synchronized SingletonCore getInstance() {
    if (instance == null) {
      instance = new SingletonCore();
    }
    return instance;
  }
//...

2/ Use “final” instance and initialize it right away instead of lazy checking:

//...
  private static final JSingleton INSTANCE = new JSingleton();

  public static synchronized JSingleton getInstance() {
    return INSTANCE;
  }
//...

The NOT recommended ones:

3/ Double-checked locking : not only because it is broken, but also it represents the most burden of development in Java: complication ! Well, everybody says that complexity in development should be avoided, but at least 90% of them still make the “mantra of Java EE” : Make things hard for things that should be much simpler.

4/ Enum : well, this is the shortest way to make an singleton which is thread-safe and serializable. It is recommended by a very big authority, to create a singleton that satisfies the constraints and still efficient (short LoC). I agree that this approach is smart, and good for exhibition. But it is not useful for most applications, because the normal apps don’t have to create an enum everytime we want a singleton. And it requires a deep knowledge about Enum implementation in Java to understand why enum is Singleton (in Java), rather than to understand the “singleton” pattern. Therefore, it may be abused by “more complicated” phenomenom, “over engineered” or “too much abstraction” … you name it. Thus, it is not recommended (by me) except in some certain situations.

5/ Inner class (Holder/Wrapper) for singleton: also not recommended , because they are more complicated than the simple ones mentioned at the begining of this article.

6/ Hashtable/boolean variable : also not good and intuitive as using null instance checking

7/ HashMap as registry: not intuitive, still complicated

8/ Combine one of above with Dependency Injection:  still complicated.

 

In short, if you prefer Keep It Simple and  YAGNI, just use the simple implementation!

 

(Feel free to leave some feedback if you think another solution is more elegant)

 

 

 

./.

 

About DucQuoc.wordpress.com

A coder, content creator, and a proud father of 2 princesses.
This entry was posted in Coding, Marketing. Bookmark the permalink.

10 Responses to Singleton In Java

  1. good post man, enjoyed reading. in my opinion Enum in Java are great feature and most versatile and very useful under certain scenario. In my opinion following are some of benefits of enum in java :
    1) Enum is type-safe you can not assign anything else other than predefined enum constant to an enum variable.
    2) Enum has its own name-space.
    By the way I have also blogged my experience as 10 examples of enum in java , let me know how do you find it.

  2. Pingback: Change Set Comments | DucQuoc's Blog

  3. Pingback: Developer Productivity Difference | DucQuoc's Blog

  4. Pingback: Eclipse WTP Tomcat hot deploy | DucQuoc's Blog

  5. Pingback: Logging best practices | DucQuoc's Blog

  6. Pingback: Personal Review 2012 | DucQuoc's Blog

  7. Pingback: Sprint end DoW | DucQuoc's Blog

  8. Pingback: HTML JavaScript playgrounds | DucQuoc's Blog

  9. Pingback: Dan ong 30 | DucQuoc's Blog

Leave a reply to DucQuoc.wordpress.com Cancel reply