Thursday, October 14, 2010

Implementing Singleton in cluster envirnoment - Option 2

This can achieved using intial context and bind the map to it.

  • Improving performance with the Singleton pattern and caching. The Singleton pattern [ GHJV95 ] ensures that only a single instance of a class exists in an application. The meaning of the term "singleton" is not always clear in a distributed environment; in ServiceLocator it means that only one instance of the class exists per class loader.
    The Singleton pattern improves performance because it eliminates unnecessary construction of ServiceLocator objects, JNDI InitialContext objects, and enables caching (see below).
    The Web-tier service locator also improves performance by caching the objects it finds. The cache lookup ensures that a JNDI lookup only occurs once for each name. Subsequent lookups come from the cache, which is typically much faster than a JNDI lookup.
    The code excerpt below demonstrates how the ServiceLocator improves performance with the Singleton pattern and an object cache.
    
    public class ServiceLocator {
    
        private InitialContext ic;
        private Map cache;
    
        private static ServiceLocator me;
    
        static {
          try {
            me = new ServiceLocator();
          } catch(ServiceLocatorException se) {
            System.err.println(se);
            se.printStackTrace(System.err);
          }
        }
       private ServiceLocator() throws ServiceLocatorException  {
          try {
            ic = new InitialContext();
            cache = Collections.synchronizedMap(new HashMap());
          } catch (NamingException ne) {
                throw new ServiceLocatorException(ne);
           }
        }
    
       static public ServiceLocator getInstance() {
          return me;
        }
              
    A private class variable me contains a reference to the only instance of the ServiceLocator class. It is constructed when the class is initialized in the static initialization block shown. The constructor initializes the instance by creating the JNDI InitialContext and the HashMap that is used a cache. Note that the no-argument constructor is private: only class ServiceLocator can construct a ServiceLocator. Because only the static initialization block creates the instance, there can be only one instance per class loader.
    Classes that use service locator access the singleton ServiceLocator instance by calling public method getInstance.
    Each object looked up has a JNDI name which, being unique, can be used as a cache HashMap key for the object. Note also that the HashMap used as a cache is synchronized so that it may be safely accessed from multiple threads that share the singleton instance.


Resource --
http://java.sun.com/blueprints/patterns/ServiceLocator.html
http://www.roseindia.net/javatutorials/J2EE_singleton_pattern.shtml

    No comments:

    Post a Comment