Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Service Locator Pattern

 
aparna chi
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class called EJBHomeFactory which as the name suggests caches the Home objects for EJB's which gives better performance since JNDI look up is not done every time.
I have one question if my object of this class contains several cached home objects and now the object of this class is not used by anyone so will it get garbage collected as no other object is referencing this factory object?
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How is your factory implemented? Often factories are realized as Singletons - the class will have a static reference to it self.
 
aparna chi
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
Here is the code for my factory:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.rmi.PortableRemoteObject;
public class EJBHomeFactory
{
private Map ejbHomes;
private static EJBHomeFactory aFactorySingleton;
InitialContext ctx;
/**
* EJB home factory private constructor
*/
private EJBHomeFactory() throws NamingException
{
ctx = new InitialContext();
this.ejbHomes = Collections.synchronizedMap(new HashMap());
}
/*
* Returns the singleton instance of EJBHomeFactory
*/
public static EJBHomeFactory getFactory()
{
try
{
if(EJBHomeFactory.aFactorySingleton == null)
{
EJBHomeFactory.aFactorySingleton = new EJBHomeFactory();
}
}catch(Exception e)
{
System.out.println("exception in static ejb home factory "+e);
}
return EJBHomeFactory.aFactorySingleton;
}
/**
* Look up and cache an EJBHome object using a home class.
*/
public EJBHome lookUpHome(Class homeClass)
{
EJBHome anEJBHome;
anEJBHome = (EJBHome)this.ejbHomes.get(homeClass);
try
{
if(anEJBHome == null)
{
anEJBHome = (EJBHome)PortableRemoteObject.narrow(ctx.lookup(homeClass.getName()), homeClass);
this.ejbHomes.put(homeClass, anEJBHome);
}
}catch(Exception e)
{
System.out.println("exception in look up home "+e);
}
return anEJBHome;
}
}
I am not sure whether the object of this class will get garbage collected if no other class in the system is referring to it.
Can you help me out with this?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic