简体   繁体   English

EJB实例变量线程安全

[英]EJB instance variables thread safety

As per my understanding, stateless EJB thread safety comes from the fact that 据我了解,无状态EJB线程安全性来自以下事实:
concurrent requests to the same SLSB will be served by different intances of that particular bean, each one with it own instance variables. 对同一个SLSB的并发请求将由该特定bean的不同实例来满足,每个实例都有其自己的实例变量。

For example if a stateless ejb has a instance variable, such as an int counter, each pooled EJB will be using a different counter variable. 例如,如果无状态ejb具有实例变量(例如int计数器),则每个池EJB将使用不同的计数器变量。

Does the same apply also with injected variables as in the following example: 是否同样适用于注入变量,如以下示例所示:

@Stateless
public class User implements UserHomeLocal, UserHomeRemote
{

    @PersistenceContext(name="J2EE")
    private EntityManager manager;
}

More generally: is there any case in wich pooled beans can share instance variables as a result of dependency injection? 更笼统地说:由于依赖项注入,池中的Bean是否可以共享实例变量?

EJB Spec says EJB规范说

The container serializes calls to each stateful and stateless session bean instance. 容器将对每个有状态和无状态会话Bean实例的调用序列化。 Most containers will support many instances of a session bean executing concurrently; 大多数容器将支持许多并发执行的会话bean实例。 however, each instance sees only a serialized sequence of method calls. 但是,每个实例只能看到序列化的方法调用序列。 Therefore, a stateful or stateless session bean does not have to be coded as reentrant 因此,有状态或无状态会话bean不必编码为可重入

That means it is thread-safe, by default. 这意味着默认情况下它是线程安全的。 No extra efforts needed. 无需额外的努力。 At the same time note that stateless beans are supposed to be "state-less". 同时请注意,无状态bean应该是“无状态”的。

It is not a good idea for a stateless bean to have mutable state. 无状态的bean具有可变状态不是一个好主意。 That is just the recipe for disaster. 那只是灾难的根源。 If you need a variable to be shared amongst all instances, it needs to be a static variable. 如果需要在所有实例之间共享变量,则它必须是静态变量。 EJB specification restricts use of static mutable variables (class level variable like a counter to track all requests to all instances). EJB规范限制使用静态可变变量(类级变量,如用于跟踪对所有实例的所有请求的计数器)。 Basically "read or write nonfinal static fields" is restricted. 基本上,“读取或写入非最终静态字段”受到限制。

So to make pooled beans to share an instance variable, that variable should be static, and final. 因此,要使池化的bean共享一个实例变量,该变量应该是静态的,并且是最终变量。 If you are looking this up for any implementation reasons, you may check out Singleton beans . 如果出于任何实现原因要查找此文件,则可以签出Singleton bean Once you create a singleton bean, you can inject that in to your session bean. 创建单例bean后,可以将其注入到会话bean中。 But I am not sure if it is worth the pain. 但是我不确定是否值得付出痛苦。

And yes,the entity manager or any such Java EE objects (eg references to Java Persistence entity managers or stateful session beans) will be shared and guaranteed to be thread-safe by default (under stateless) 是的,实体管理器或任何此类Java EE对象(例如,对Java Persistence实体管理器或有状态会话Bean的引用)将被共享,并保证默认情况下是线程安全的(在无状态下)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM