问题
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:
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.
来源:https://stackoverflow.com/questions/9064605/connection-handling-in-ejb2-session-beans