Skip to content

Singletons : Is Anti-Pattern?

December 2, 2009

This was one of the long pending topic that stroked me when I was trying to create a Singleton class sometime back. What I wanted to have was a cache manager –  A CacheManager which holds all the name value pairs that were globally used by the application. So I decided to use Singleton since I would like to have global access to the NV pairs and also I would like to maintain a single instance of  the class. I made sure that  it worked with “Initialization on Demand Holder”  (lazy initialization) .

public class CacheManager {

private static final CacheManager m_instance = null;

public static CacheManager getInstance() {

if(m_instance==null)

synchronized(CacheManager.Class){

if(m_instance==null)

m_instance=new CacheManager();

}

return m_instance;

}

private CacheManager() {

//empty

}

}

Was double checking done? yes, done. Was synchronized used? yes, used.  Was ‘synchronized’  blocking the entire method and making the method costly? No, the code was blocked only when the object was created. Fine. I was happy with the CacheManager.

It worked well  for sometime and showed its bad face when multiple threads were involved.  I found that Double-checked locking was not guaranteed to work in multi threaded environment-“Double checked locking is broken-declaration”

To make it work under multiple threads, I gave up the lazy loaded feature. What if the CacheManager was initialized and was never used, the code would work  insanely. It was the pay for the thread safe implementation.

public class CacheManager{
private CacheManager() {}
private static class CacheHolder {
private static CacheManager instance = new CacheManager();
}
public static Singleton getInstance() {
return CacheHolder.instance;
}
}

Then I learned from here that, Singletons is a lie – there can be more than one instance of Singleton classes.

“When copies of the Singleton class run in multiple VMs, an instance is created for each machine.”

“When two class loaders load a class, you actually have two copies of the class, and each one can have its own Singleton instance.”

“Copies of a Singleton Object that has Undergone Serialization and Deserialization.”

Singletons cheat us from design perspective too – here, here and here.

It violates the  OO concepts of  Single Responsiblity Principle – Singleton enforces the instance policy and provides the access to configuration.

There is no way to subtype the Singleton class as the initialization cannot be overridden and there are static methods in it.

Singleton makes the unit testing harder as there is no way to mock it.

It maintains its state throughout the application and Persistent states are hard to test.

Singleton hide the dependencies and make the classes tightly coupled with each other.

Singletons are acceptable in few cases and there are some “cleaner” ways of achieving singleton benefits.  Here, Misko clearly points that Singletons are useful when there is one way flow in the application.

“Logging is perfect example. It is loaded with Singletons and global state. It is acceptable (as in it will not hurt you) because your application does not behave any different whether or not a given logger is enabled. The information here flows one way: From your application into the logger. Even thought loggers are global state since no information flows from loggers into your application, loggers are acceptable. You should still inject your logger if you want your test to assert that something is getting logged, but in general Loggers are not harmful despite being full of state.”

So,

1. Don’t use Singletons for its “GLOBAL STATE”

2. Use Singletons as STATELESS Object or as IMMUTABLE objects.

3. Use Singletons by dependency injection and make it loosely coupled with others.

Advertisements
One Comment leave one →
  1. Shyamala permalink
    January 5, 2010 9:28 am

    Hi Abirami,
    Realized the real face of Singletons. Was wondering how most of our code works fine with so many singleton classes being used 😉
    Just started reading ur blog,really good and useful.
    Keep writing more
    -Shyamala

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: