views:

204

answers:

2

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?

+1  A: 

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.

djna
+1  A: 

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.

skaffman
Interesting. I can imagine scenarios where a container might choose to respond to stress by effectively having a zero pool size, and I can imagine choosing to configure no pooling. I can also see that the latter of the spec would allow a container to create a new instance for each request, but is that actually encountered in useful production-quality environments?
djna
I doubt it, but the spec *does* permit it, and so the code shouldn't assume otherwise, *unless* you explicitly constrain the container config.
skaffman