如何在java中创建一个真正的单例? [英] How to create a true singleton in java?

查看:214
本文介绍了如何在java中创建一个真正的单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多个类加载器中使用时,我遇到了我的单例问题。 E.g由多个EJB访问的Singleton。有没有办法创建一个在所有类加载器中只有一个实例的单例?

I am facing a problem with my singleton when used across multiple class loaders. E.g Singleton accessed by multiple EJBs. Is there any way to create a singleton which has only one instance across all class loader?

我正在寻找使用自定义类加载器或其他方式的纯java解决方案。

I am looking for pure java solution either using custom class loader or some other way.

推荐答案

JavaEE应用服务器通常通过将单例设置为服务来解决此问题,其中包含其精确定义和配置取决于有问题的appserver。

JavaEE app servers generally solve this problem by setting up the singleton as a "service", the exact definition and configuration of which depends on the appserver in question.

例如,在JBoss中,您可以使用xyz-service.xml描述符来设置挂起JNDI或JMX树的单例对象,以及您的应用程序组件(例如你的EJB)将从树中获取单例。这在一定程度上保护了你的基础类加载器语义。

For example, in JBoss you could use a xyz-service.xml descriptor to set up a singleton object that hangs off the JNDI or JMX tree, and your application components (e.g. your EJBs) would fetch the singleton from the tree. That protects you to some extent from the underlying classloader semantics.

这篇关于如何在java中创建一个真正的单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆