• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Singleton implementation - Double check

 
Ranch Hand
Posts: 120
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 80874
506
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Is this a correct/good Practice? or private static final is better??
 
reply
    Bookmark Topic Watch Topic
  • New Topic