• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Singleton implementation - Double check

 
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 ;-)

 
Marshal
Posts: 64705
225
  • 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??
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!