0

I recently started maintaining an old EJB2 application running on OC4J. That includes EJB doclet and other horrible horrible things. Currently, each method creates a ConnectionFactory that queries JNDI for a Datasource, which then creates a connection. This leads to a lot of boiler plate code.

My question now is: is it safe to do this only once per stateless session bean, and reuse the same connection? ejbCreate() would get the connection from JNDI, and then close it in ejbRemove().
Would this be good or bad design?

1 Answer 1

1

The proposed design will have unpredictable behavior, as the life cycle methods are handled by the container. Stateless session bean are pooled by the container(in most cases) & same instance can be served to multiple requests.

The methods ejbCreate() and ejbRemove() are invoked by the container when the bean is initialized first time & when it is removed from the pool respectively. Therefore it may open a connection in ejbCreate(), but may not close it & service requests with the same connection.

But, if connection is opened & the bean remains idle in the pool, it will hold up resource unnecessarily, may end up in exceptions like socket timeout, too many opened connections etc.

Its better to write a generalize method for opening/closing connection, to utilize the resources properly.


Edit : From Core J2EE Patterns - Service Locator

Use a Service Locator object to abstract all JNDI usage and to hide the complexities of initial context creation, EJB home object lookup, and EJB object re-creation. Multiple clients can reuse the Service Locator object to reduce code complexity, provide a single point of control, and improve performance by providing a caching facility.

3
  • How about other session beans? Are those safe to "cache" (initialize in ejbCreate) in session beans, like I'm currently doing with connections? Jan 31, 2012 at 8:49
  • Please refer edit part for caching of stateless beans, these beans should not contain instance variables. Jan 31, 2012 at 17:14
  • Note that it is advisable to have instance variables if they consume resources & are shareable, like caching of some data from database. Feb 1, 2012 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.