问题描述
我正在关注也使用EJB的:
I'm following this tutorial which also uses an EJB:
package exercise1;
import java.util.Random;
import javax.ejb.Stateless;
import javax.inject.Named;
@Stateless
public class MessageServerBean {
private int counter = 0;
public String getMessage(){
Random random = new Random();
random.nextInt(9999999);
int myRandomNumber = random.nextInt();
return "" + myRandomNumber;
}
public int getCounter(){
return counter++;
}
}
这是一个输出示例:
您好,从Facelets
消息是:84804258
计数器是:26
消息服务器Bean是:exercise1.MessageServerBean@757b6193
Hello from Facelets
Message is: 84804258
Counter is: 26
Message Server Bean is: exercise1.MessageServerBean@757b6193
这是我的观察:
- 当我将bean设置为
@Stateless
时,我总是得到相同的对象ID,计数器总是递增。 - 当我将bean设置为
@Stateful
时,每次刷新页面时,都会收到一个新的实例。 - 当我将它设置为
@Singleton
时,我得到的结果与我设置为@Stateless
:相同的对象ID,计数器递增。
- When I set the bean as
@Stateless
I always get the same object ID and counter always increments. - When I set the bean as
@Stateful
I get a new instance every time I refresh the page. - When I set it to
@Singleton
I get the same results as when I set it to@Stateless
: same object ID, counter incrementing.
所以,我实际想了解的是: @Stateless
和 @Singleton
EJBs在这种情况下
So, what I actually would like to understand is: what's the difference between @Stateless
and @Singleton
EJBs in this very case?
推荐答案
您看到相同的输出,因为一次只有一个客户端访问EJB。应用服务器能够为每个呼叫回收相同的无状态EJB对象。如果您同时尝试并发访问多个客户端,则会显示新的无状态实例。
You're seeing the same output because there is only one client accessing the EJB at a time. The application server is able to recycle the same stateless EJB object for each call. If you try a concurrent access – multiple clients at the same time - you'll see new stateless instances appearing.
请注意,根据服务器负载,连续两个同一客户端进行的方法调用可能会导致不同的无状态EJB对象!
Note that, depending on the server load, even two consecutive method invocations made by the same client may end up in different stateless EJB objects!
对于单例EJB,没有区别 - 每个应用程序总是只有一个实例,无论有多少客户端尝试访问它。
For a singleton EJB, there will no difference – there is always only one instance per application, no matter how many clients try to access it.
这篇关于@Stateless和@Singleton之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!