Static vs Instance members in Stateless EJBs
Asked Answered
B

3

1

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?

Bedrabble answered 13/10, 2009 at 7:18 Comment(0)
W
1

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.

Winifredwinikka answered 13/10, 2009 at 7:24 Comment(0)
L
1

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.

Larisalarissa answered 13/10, 2009 at 7:27 Comment(2)
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?Winifredwinikka
I doubt it, but the spec does permit it, and so the code shouldn't assume otherwise, unless you explicitly constrain the container config.Larisalarissa
D
0

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.

Dimeter answered 26/10, 2012 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.