• Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton implementation - Double check  RSS feed

 
sandeep lokhande
Ranch Hand
Posts: 120
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In implementing Singleton Class,


Why we check twice(LN 2) when we are checking later(LN 5) ???


 
sandeep lokhande
Ranch Hand
Posts: 120
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sandeep lokhande wrote:In implementing Singleton Class,


Why we check twice(LN 2) when we are checking later(LN 5) ???




While waiting for answer i was googling and i found satisfatory answer,
Its a huge overhead because everytime the method is invokes synchronized has to go through the process of waiting for the lock and then obtaining the lock and
its unnecessary because its only once that the instance is created and all subsequent invocations would just return that instance. :-) so00 simple ;-)

 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you implementing a singleton in the first place?
You do realise that double‑checked locking doesn’t work in Java? Well, I think it does work in Java5+.
I think you need to create a static instance. No need to mess around with synchronisation or null checks.I think that is correct; it looks the same as in my Effective Java™ (Joshua Bloch) page 18. But Bloch points out there is now a far better way to create a Singleton: use an enum.
 
sandeep lokhande
Ranch Hand
Posts: 120
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Is this a correct/good Practice? or private static final is better??
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!