Connection handling in EJB2 session beans
Asked Answered
P

1

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?

Profuse answered 30/1, 2012 at 13:27 Comment(0)
L
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.

Liquidize answered 30/1, 2012 at 19:19 Comment(3)
How about other session beans? Are those safe to "cache" (initialize in ejbCreate) in session beans, like I'm currently doing with connections?Profuse
Please refer edit part for caching of stateless beans, these beans should not contain instance variables.Liquidize
Note that it is advisable to have instance variables if they consume resources & are shareable, like caching of some data from database.Liquidize

© 2022 - 2024 — McMap. All rights reserved.