Static vs Instance members in Stateless EJBs

旧巷老猫 提交于 2019-12-24 08:48:34

问题


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:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1558646/static-vs-instance-members-in-stateless-ejbs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!