Alex Rivera | Logout

Problems with Singleton Pattern

Asked 2009-09-08T06:37:30.767
51

I've been reading about Singleton pattern for last few days. The general perception is that the scenarios where it is required are quite few (if not rare) probably because it has its own set of problems such as

  • In a garbage collection environment it can be an issue with regards to memory management.
  • In a multithreaded environment it can cause bottlenecks and introduce synchronization problems.
  • Headache from testing prespective.

I'm starting to get the ideas behind these issues but not totally sure about these concerns. Like in case of garbage collection issue, usage of static in singleton implementation (which is inherent to the pattern), is that the concern? Since it would mean that the static instance will last till the application. Is it something that degrades memory management (it just means that the memory allocated to the singleton pattern won't be freed)?

Ofcourse in a multithreaded setup, having all the threads being in contention for the singleton instance would be a bottleneck. But how does usage of this pattern causes synchronization problems (surely we can use a mutex or something like that to synchronize access).

From a (unit?)testing perspective, since singletons use static methods (which are difficult to be mocked or stubbed) they can cause problems. Not sure about this. Can someone please elaborate on this testing concern?

Thanks.

Edit
Report

1 Answer

30

If you haven't seen the article Singletons are Pathological Liars, you should read that too. It discusses how the interconnections between singletons are hidden from the interface, so the way you need to construct software is also hidden from the interface.

There are links to a couple of other articles on singletons by the same author.

answered 2009-09-08T06:47:15.250

Your Answer