Skip to main content

Posts

Showing posts from February, 2014

How to make singleton thread-safe

refer link:  http://www.javagyan.com/useful-tips/howtocreatethread-safesingleton A singleton class should be designed to ensures that there exists only one instance per application. Special care must be taken if your application is deployed on a clustered environment as in this case it is possible that multiple instance of your singleton class are available in your application.    Here are a few ways to create a thread safe singleton classes in your application.  1) Lazy loading Singleton instance - Using Synchronized method or block public class SingletonClass{     private SingletonClass sc;     private SingletonClass(){}     public static SingletonClass getInstance(){         synchronized(SingletonClass.class) {               if (sc == null) {                   sc = new SingletonClass();               } else {                  return sc;               }         }     } } Issues - The use of synchronized keyword in a singleton class means that only one thread will be executing th