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.