Created
March 28, 2013 19:29
-
-
Save silvercircle/5266114 to your computer and use it in GitHub Desktop.
Singleton class, implemented using the "Pugh" Method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package at.or.miranda; | |
/** | |
* Singleton class with as-lazy-as-possible initialization not requiring | |
* explicit locking mechanisms. | |
* | |
* Also known as the "Pugh method" and generally accepted as a standard for creating | |
* singleton objects in a thread safe way. | |
* | |
* To fully understand this, it is necessary to understand how the class loader | |
* loads and initializes classes. | |
*/ | |
public class SingletonTestOnDemand { | |
private String hi = null; | |
/** | |
* constructor kept private to prevent access from the outside (= it is not possible | |
* to create objects of this class other than accessing the static method getInstance() | |
*/ | |
private SingletonTestOnDemand() { | |
hi = "I'm a singleton with on-demand holder initialization"; | |
} | |
public void greet() { | |
System.out.println(hi); | |
} | |
/** | |
* the class loader will initialize the InstanceHolder class on the first access (and only once, | |
* of course, according to Java class loading and initializing rules). | |
* | |
* so when getInstance() is called for the first time, an object of SingletonTestOnDemand will | |
* be instantiated through the initialization process of the InstanceHolder class. | |
* | |
* Since the class loader is thread-safe by default, no explicit locking mechanism is required | |
* to guarantee thread-safe instantiation | |
*/ | |
private static final class InstanceHolder { | |
/** | |
* the member can be public, because the class itself is private and thus not | |
* accessible from the outside | |
*/ | |
public static final SingletonTestOnDemand _instance = new SingletonTestOnDemand(); | |
} | |
public static SingletonTestOnDemand getInstance() { | |
/** | |
* The InstanceHolder class will be initialized at first access, thus creating the | |
* object. | |
*/ | |
return InstanceHolder._instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment