- 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; inServiceLocator
it means that only one instance of the class exists per class loader.
The Singleton pattern improves performance because it eliminates unnecessary construction ofServiceLocator
objects, JNDIInitialContext
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 theServiceLocator
improves performance with the Singleton pattern and an object cache.
A private class variablepublic 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; }
me
contains a reference to the only instance of theServiceLocator
class. It is constructed when the class is initialized in the static initialization block shown. The constructor initializes the instance by creating the JNDIInitialContext
and theHashMap
that is used a cache. Note that the no-argument constructor isprivate
: only classServiceLocator
can construct aServiceLocator
. 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 singletonServiceLocator
instance by calling public methodgetInstance
.
Each object looked up has a JNDI name which, being unique, can be used as a cacheHashMap
key for the object. Note also that theHashMap
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