Home and StateLessSessionBean thread safety


EJB programming & troubleshooting: Home and StateLessSessionBean thread safety

  1. Home and StateLessSessionBean thread safety (3 messages)


    My understanding is that a home interface is thread safe and is thus a good candidate for cacheing, thus eliminating the jndi lookup. Can someone confirm this?

    Also, as I uderstand StatelessSessionBeans, the container may swap/re-use instances behind the scenes and also ensures that there is only one thread of execution per instance. Now if my client class has an instance variable which is a stateless session bean, is this also thread safe? Is this bean also a candidate for cacheing? Is this implementation specific and outside of the scope of the spec?


  2. The home interfaces can be cached, there is a pattern described on this site for doing this.

    As for the stateless EJB, your client can cache the remote interface if necessary. Any calls will be routed to any available stateless EJB, ie. you cannot be sure that one method call will be processed by the same EJB as the next method call.

  3. Thanks Rick,

    But Im still not 100% certain on thread issues with stateless session beans. Say I have an instance(remote stub) of a session bean in a servlet, then I may have many concurrent requests (threads) going through that instance. Hence if this is allowed, there would be no need to cache the home interface as all requests can pass through the same stub. Hence its still not clear to me if this is good or bad practice.

    As *I* understand RMI, this should work fine, but I don't want to get burnt down the track...


  4. Home and StateLessSessionBean thread safety[ Go to top ]

    The Stateless Session Bean itself is thread-safe. What this means, however, is that it is guaranteed by the container that only one thread will be allowed inside a bean at any point of time.

    In the scenario you mentioned, of multiple servlet threads calling the same bean instance (i.e the same EJBObject), the following will happen: The first thread that enters the bean (via the EJBObject) will be processed fine. If a second thread tries to call a method on the bean *while the first thread is still running*, you would get a RemoteException.

    Moreover, according to the specs, "a session object is intended to support only a single client. Therefore, it would be an application error if two clients attempted to invoke the same session object."

    So, I don't think storing the Remote interface as a servlet attribute is a good idea. Thus the need for the EJBHomeFactory for frequent JNDI lookups!

    For more details, check out the specs: PFD2 6.11.6, 14.8.3

    Hope this helps,