使用 JBoss SEAM 进行单例
我有以下代码:
@Name("myService")
@Scope(ScopeType.APPLICATION)
@Stateless
public class MyService {
private Service service;
private Service getService() {
if (service == null) {
service = Service.create(url, new QName("URL",
"Envelope"));
}
return service;
}
public synchronized Port getPort() {
return getService().getPort();
}
}
getPort 方法是从不同的线程调用的。 “Service.create”花费了很多时间,我发现实际上它被调用了不止一次。因此,看起来好像创建了多个 MyService 类实例,这就是 synchronized 没有帮助的原因。
我已将注释更改为:
@AutoCreate
@Startup
@Name("myService")
@Scope(ScopeType.APPLICATION)
现在似乎工作正常:仅创建一个实例,并且同步对 getPort() 方法的访问。
谁能解释为什么第一个案例没有按预期进行?
I have the following code:
@Name("myService")
@Scope(ScopeType.APPLICATION)
@Stateless
public class MyService {
private Service service;
private Service getService() {
if (service == null) {
service = Service.create(url, new QName("URL",
"Envelope"));
}
return service;
}
public synchronized Port getPort() {
return getService().getPort();
}
}
And getPort method is invoked from different threads. "Service.create" takes a lot of time and I've found that actually it is invoked more than once. So it looks like more than one instance of MyService class is created and that's why synchronized doesn't help.
I've changed annotations to:
@AutoCreate
@Startup
@Name("myService")
@Scope(ScopeType.APPLICATION)
And now it seems to work fine: only one instance is created and access to the getPort() method is synchronized.
Could anyone explain why the first case doesn't wok as expected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
绑定到 Application 作用域的 @Stateless 是一个矛盾修饰法,
您要求 Java EE 提供一个没有状态的组件,位于 Application 作用域中,由所有用户共享
当您删除 @Stateless 注释时,seam 处理了该实例组件并将其放置在应用程序范围中,它也在启动时创建它,因此有一个单例
A @Stateless bound to an Application scope is an oxymoron
you are asking Java EE to provide a component that has no state, to live in the Application Scope, shared by all users
When you removed the @Stateless annotation, seam handled the instance of the component and placed it in the Application Scope, it also created it at startup, hence having a singleton