Question

I have a stateless session bean which needs access to a factory class. Is it best to declare this factory class as a static or instance member in the SLSB? Am I correct in saying that, as SLSBs are reused, only one instance of the factory will be created per bean (when going with the instance member option), as opposed to one instance per request?

Was it helpful?

Solution

SLSB instances are pooled, and hence serve potentially many requests over their lifetime, so as you say instance variables are not recreated for each request.

The "natural" way for SLSB is to have each instance independent, no statics, no need for synchronisation between instances. Hence if it's possible I'd have a factory instance per SLSB instance.

OTHER TIPS

Don't assume that an instance of the SLB will not be created per request. The container is within its rights to create one every request; equally, it is also allowed to have only a single instance (I think). More generally, the container will maintain a pool of them.

If instantiating and/or initialising your SLSB is relatively expensive, you should investigate exactly what your container will do, and if possible configure it explicitly to what you want it to do.

Assuming you do that, then there should be no problem with keeping an instance field in the SLSB class.

Instance variables are not recreated as long as the SLSB is reused from the pool. The lifecycle of SLSB is rather simple: create an instance, use it n times to attend n requests, and eventually throw it away. All these actions are performed by the container. So in the creation process of the bean (controlled by us) we can initialize these instance variables. But never modify the contents of these variables once they are initialised in order to avoid side effects.

You can use static instances if you wish to, but bear in mind that you must handle the synchronization issues by hand; and furthermore, you are constrained to a local factory.

A very elegant solution is provided by EJB 3.1 with the @Singleton EJBs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top