Last active
October 14, 2015 01:37
-
-
Save raskasa/4287173 to your computer and use it in GitHub Desktop.
A basic implementation of the Singleton design pattern for reference.
This file contains 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
/** | |
* A basic implementation of the Singleton design pattern for reference. | |
*/ | |
public class Singleton { | |
/** | |
* Stores the only instance of this object. The 'volatile' keyword ensures | |
* that multiple threads handle the uniqueInstance variable correctly when it | |
* is being initialized to the Singleton instance. | |
*/ | |
private volatile static Singleton uniqueInstance; | |
/** | |
* Private constructor so that this class cannot be instanstiated directly. | |
*/ | |
private Singleton() { | |
} | |
/** | |
* Returns the ONLY instance of the Singleton; creates a new instance if one has | |
* not been instantiated already. | |
* | |
* MULTITHREADING (CONCURRENCY): | |
* We can easily deal with multithreading issues by synchronizing this method like so: | |
* | |
* public static synchronized Singleton getInstance() {} | |
* | |
* By adding the synchronized keyword to this method, we force evey thread to wait its | |
* turn before it can enter the method. That is, no two threads may enter the method | |
* at the same time. Synchronization in getInstance() is expensive - this is an issue. | |
* The only time synchronization is relevant is the first time through it. In other | |
* words, once we've set the uniqueInstance variable to an instance of Singleton, we | |
* have no further need to synchronize this method. After the first time through, | |
* synchronization is totally unneeded overhead! | |
* | |
* SOLUTION: | |
* A better solution is to use double-checked locking to reduce the use of | |
* synchronization in getInstance(). With double-checked locking, we first chekc to | |
* see if an instance is created, and if not, THEN we synchronize. This way, we only | |
* synchronize the first time through. | |
* | |
* TAKEAWAY: | |
* If performance is an issue in your use of this method, then this method of | |
* implementing the Singleton can drastically reduce the overhead. | |
* | |
* CAVEAT: | |
* Double-checked locking is not supported in Java version 1.4 and earlier | |
*/ | |
public static Singleton getInstance() { | |
if (uniqueInstance == null) { // NOTE: we only synchronize the first time through. | |
synchronized (Singleton.class) { | |
if (uniqueInstance == null) { | |
uniqueInstance = new Singleton(); | |
} | |
} | |
} | |
return uniqueInstance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment