使用 JBoss SEAM 进行单例

发布于 2024-11-09 08:05:20 字数 737 浏览 0 评论 0原文

我有以下代码:

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海少女心 2024-11-16 08:05:20

绑定到 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文