wood burning stoves 2.0*
The moose likes Java in General and the fly likes Singleton class + Lazy loading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Singleton class + Lazy loading" Watch "Singleton class + Lazy loading" New topic

Singleton class + Lazy loading

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1372
How can i load Singleton class using lazy loading?
Rob Spoor

Joined: Oct 27, 2005
Posts: 19656

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.

How To Ask Questions How To Answer Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Don't get me started about those stupid light bulbs.
subject: Singleton class + Lazy loading
Similar Threads
Singleton - Initialization On Demand Holder.
Dynamic class loading and lazy loading
How to avoid loading of all static variables when JVM encounter JAVA class name
lazy loading