EJB 3 中的类变量是线程安全的吗?
在servlet中,因为它是单例的,除了实现SingleThreadModel
。参考这篇文章 https://www.fortify.com/vulncat/en/ vulncat/java/singleton_member_field_race_condition.html
但是在EJB 3中,我找不到类似的文档。因为容器将创建一个池来处理 EJB。我认为类变量应该是安全的,对吗?
例如,classVar1
是一个类变量,我在构造函数中初始化它并稍后使用它。在servlet中,可能有问题,但是在EJB 3中,应该没问题吧?
@Stateles
public class HelloBean implements Hello {
ObjectXXX classVar1;
public HelloBean() {
ObjectXXX classVar1 = new ObjectXXX();
}
public String doHello(String message) {
return message + classVar1.method1();
}
}
还有一个问题是,注入到EJB的资源(即JPA中的EntityManager),它应该是线程安全的吗?
In servlet, because it's singleton except implement SingleThreadModel
. Reference this article https://www.fortify.com/vulncat/en/vulncat/java/singleton_member_field_race_condition.html
But in EJB 3, I cannot find a similar document. And because container will create a pool to handle EJBs. I think the class variable should be safe, is it correct?
For example, classVar1
is a class variable, I initial it in constructor and use it later. In servlet, it may have problem, but in EJB 3, it should be ok, right?
@Stateles
public class HelloBean implements Hello {
ObjectXXX classVar1;
public HelloBean() {
ObjectXXX classVar1 = new ObjectXXX();
}
public String doHello(String message) {
return message + classVar1.method1();
}
}
And another question is that the resource (i.e. EntityManager
in JPA) injected to EJB, it should be thread safe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
容器必须只允许 1 个线程在特定的 EJB 实例中,因此:每个方法只能由一个线程执行,并且您的变量是“安全的”(当您在构造函数或 @PostConstruct 方法中初始化它时) )。
但是,SLSB(无状态EJB)不应该用于保持状态。 EJB 是池化的,因此您无法保证会返回到同一个实例。 SFSB 就是为此目的而设计的。
EntityManager 与 EJB 中的每个实例字段一样,都是线程安全的。
但是,EntityManager本身不是线程安全,不能在超过1个线程可以访问它的环境中使用(即在Servlet中)。在这种情况下,应改用 EntityManagerFactory。
The container must let only 1 thread in particular EJB instance, so: each method can be executed by only a single thread and your variable is 'safe' (as you initialize it in the constructor or
@PostConstruct
method).However, the SLSB (stateless EJB) should not be used to keep a state. The EJB is pooled, so you don't have any guarantee that you will return to the same instance. The SFSB is made for this purpose.
The EntityManager, as every instance field in the EJB, is thread safe.
However, the EntityManager itself is not thread safe and cannot be used in environment where more than 1 thread can access it (i.e. in Servlet).
EntityManagerFactory
should be used instead in such cases.