users@glassfish.java.net

Re: Stateful Session Bean [One instance per client ? Really ?]

From: <glassfish_at_javadesktop.org>
Date: Sun, 30 Nov 2008 10:56:08 PST

It's up to the client to access the same session object.
In order to get the same one, you should cache your ejbSession in some data structure, so when you need it next time you get it from there (see method getService below):

public class ServiceLocator {
     /**
      * Singleton Instance of this class
      */
     private static ServiceLocator serviceLocator = null;

    // just for the test
     private static int counter = 0;
     
     /**
      * InitialContext object
      */
     InitialContext context = null;

     /**
      * Cache where the objects can be stored for later
      * retrieval.
      * This enhances the performance.
      */
     HashMap serviceCache = null;

    /**
     * Constructor to initialize the class
     *
     * @exception NamingException In case an exception is
     * generated
     */
     public ServiceLocator() throws NamingException {
      // Start the initial context
      context = new InitialContext();
      // Initialize the HashMap to store 5 objects
      serviceCache = new HashMap(5);
     }
    
    /**
     * Returns the singleton instance
     *
     * @exception NamingException In case an exception is
     * generated
     * @return Singleton Instance
     */
   public synchronized static ServiceLocator getInstance() throws NamingException {
      if (serviceLocator == null) {
        // If the object is not created, then create it
        serviceLocator = new ServiceLocator();
      }

      // Return the singleton instance
      return serviceLocator;
    }
    
    /**
     * This is the method that returns the service
     *
     * @param jndiName JNDI Lookup needed for invoking the
     * service
     * @exception NamingException In case an exception is
     * generated
     * @return Service Object
     */
    public Object getService(String jndiName) throws NamingException {
      if (!serviceCache.containsKey(jndiName)) {
        // If the object is not saved in the cache, then do a
        //lookup and save it
        serviceCache.put(jndiName, context.lookup(jndiName));
      }
      // Return the required object
      return serviceCache.get(jndiName);
    }
    

}
[Message sent by forum member 'sorincalex' (sorincalex)]

http://forums.java.net/jive/thread.jspa?messageID=319244