Static vs Instance elements in stateless EJB

I have a beanless session that needs access to the factory class. Is it better to declare this class factory as a static or instance member in SLSB? Am I right in saying that since SLSBs are reused, only one factory instance will be created per bean (when going with the instance member parameter), as opposed to a single instance for the request?

+1
source share
3 answers

SLSB instances are merged and therefore serve potentially many requests throughout their life cycle, since you say that instance variables are not recreated for each request.

The β€œnatural” way for SLSB is the independence of each instance, the lack of statics, the lack of synchronization between instances. Therefore, if possible, I will have a factory instance for the SLSB instance.

+1
source

Do not assume that an SLB instance will not be created for each request. The container is within its rights to create each request; Equally, it is also allowed to have only one instance (I think). More generally, the container will contain a pool of them.

If creating and / or initializing your SLSB is relatively expensive, you should find out what your container will do, and if possible, configure it explicitly for what you want.

Assuming you did this, then there should be no problem saving the instance field in the SLSB class.

+1
source

Instance variables are not recreated if the SLSB is reused from the pool. The SLSB life cycle is quite simple: create an instance, use it n times to visit n requests, and finally throw it away. All these actions are performed by the container. Thus, in the process of creating a bean (controlled by us), we can initialize these instance variables. But never modify the contents of these variables after they are initialized to avoid side effects.

You can use static instances if you want, but remember that you must manually handle synchronization problems; and furthermore, you are limited to a local factory.

A very elegant solution is provided by EJB 3.1 using EJB @Singleton.

0
source

Source: https://habr.com/ru/post/885782/


All Articles