This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton class + Lazy loading

 
kri shan
Ranch Hand
Posts: 1460
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can i load Singleton class using lazy loading?
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are several ways.

The easiest way is to make the entire getInstance() method synchronized. A bit harder is double-checked locking:
Then there is the holder class:
This nested class will only be initialized when needed; that is, when Singleton.getInstance() is called. Only then will it create the Singleton object. Since class loading is atomic, this approach is thread safe as well.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that double-checked locking is tricky, and it will not work correctly if you use an older Java version than Java 5: The "Double-Checked Locking is Broken" Declaration.

As far as I know, the memory model was changed in Java 5 so that it's no longer broken (I don't remember all the details right now), but it's still tricky.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic