Thread Safe Singleton
Writing by shivdev on Saturday, 22 of December , 2007 at 2:09 pm
Here is an example of a Simple Singleton. There are 3 things to remember.
- Create a private static instance of the singleton class.
- The constructor must be private.
- There must be a static method to get the “single” instance of the singleton class.
/* This is NOT Thread Safe - This is a Simple Example of a Singleton*/ public class SimpleSingleton { private static SimpleSingleton instance = null; private SimpleSingleton () { } public static SimpleSingleton getInstance() { // lazily create an instance if (instance == null) { instance = new SimpleSingleton (); } return instance; } }
Now here is an example of a Thread Safe Singleton achieved using the synchronized(instance). The reason for checking (instance == null) twice is so that we don’t want all threads to wait when getInstance() is called. Threads must wait only when instance is being created.
public class ThreadSafeSingleton { private static ThreadSafeSingleton instance = null; private ThreadSafeSingleton() { } public static ThreadSafeSingleton getInstance() { // Threads will acquire a lock and wait ONLY if instance is NOT NULL if (instance == null) { // Only One Thread allowed at a time from this point synchronized (instance) { if (instance == null) { instance = new ThreadSafeSingleton(); } } // End of Synchronized Block } return instance; } }
Another Thread Safe Singleton Example
Another way of achieving a Thread Safe Singleton without worrying about synchronization, is by instantiating the Singleton object when the CLASS gets loaded (in the static block). However, the we lose the “lazy initialization” nature of the ThreadSafeSingleton shown above.
public class Singleton { static { // This happens when the class is loaded. instance = new Singleton(); } private static Singleton instance = null; private Singleton () { } public static Singleton getInstance() { return instance; } }
Leave a comment
- Add this post to
- Del.icio.us -
- Digg -
- -
- Tweet -
-
-
No comments yet.
You must be logged in to post a comment.