• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Singleton Design Pattern using double checked lock  RSS feed

 
Mr. Vipul Gupta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This post is an example to use Singleton Design Pattern in java in Multi-threaded environment using double checked lock.
Here is the link:
Java Singleton Design Pattern Example

Thanks,
_______________________________________________________________________
Java Atomic Variable Docker Interview Questions
Docker Basics
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch,

I'm sorry, but the advice in that link is outdated and horribly wrong. Double checked locking simply doesn't work.

If you really need lazy initialization of a singleton (which I doubt), there are other ways that are not inherently broken.
 
Mr. Vipul Gupta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stephan for the analysis.

Double checked lock was broken till jdk4 and below. With jdk5 and above, double checked locking is no longer broken if we declare the Singleton object as volatile.




 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Except that accessing a volatile field will incur half the cost of entering a synchronized block, so effectively you've made no performance gains over just making the entire getInstance() method synchronized.

All of this is assuming that creating the singleton object is expensive. Before you dive into loading it lazily, you should profile the application and see if accessing it multiple times is really a performance bottleneck.

Finally, I will take the opportunity to once again express that "Singletons are EVIL". Unless they are constant (even between different application executions), they represent variable state. Such state should never globally accessible, because it prevents you from effectively unit-testing your application.

Classes shouldn't pull what they need out of thin air. You should provide it to them in their constructors or methods:

The difference between the two is that in the first example, you're forever stuck with the same repository that everybody can access. This makes it hard to test, hard to debug and inflexible. In the second example, you tell the controller what repository to use, and if it needs to be the same repository throughout the entire application, you just create one and pass that to everything that needs a repository.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!