java - Java中如何创建跨进程的Singleton类

标签 java

是否可以创建一个通用的 Singleton 类,即在任何给定时间,多个 Java 进程之间只共享一个实例?

最佳答案

多个 Java 进程不共享同一个虚拟机。

因此,您最终会得到一个托管单例的 JVM 实例,然后每个进程一个 JVM 实例使用远程方法调用访问单例,正如@Little Bobby Tables 所建议的那样。

无论如何考虑When is a Singleton not a Singleton :

Multiple Singletons in Two or More Virtual Machines

When copies of the Singleton class run in multiple VMs, an instance is created for each machine. That each VM can hold its own Singleton might seem obvious but, in distributed systems such as those using EJBs, Jini, and RMI, it's not so simple. Since intermediate layers can hide the distributed technologies, to tell where an object is really instantiated may be difficult.

For example, only the EJB container decides how and when to create EJB objects or to recycle existing ones. The EJB may exist in a different VM from the code that calls it. Moreover, a single EJB can be instantiated simultaneously in several VMs. For a stateless session bean, multiple calls to what appears, to your code, to be one instance could actually be calls to different instances on different VMs. Even an entity EJB can be saved through a persistence mechanism between calls, so that you have no idea what instance answers your method calls. (The primary key that is part of the entity bean spec is needed precisely because referential identity is of no use in identifying the bean.)

The EJB containers' ability to spread the identity of a single EJB instance across multiple VMs causes confusion if you try to write a Singleton in the context of an EJB. The instance fields of the Singleton will not be globally unique. Because several VMs are involved for what appears to be the same object, several Singleton objects might be brought into existence.

Systems based on distributed technologies such as EJB, RMI, and Jini should avoid Singletons that hold state. Singletons that do not hold state but simply control access to resources are also not appropriate for EJBs, since resource management is the role of the EJB container. However, in other distributed systems, Singleton objects that control resources may be used on the understanding that they are not unique in the distributed system, just in the particular VM.

关于java - Java中如何创建跨进程的Singleton类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2810378/

相关文章:

java - 自定义类加载器问题

java - 使用 sendkeys 时,Web 驱动程序会跳过特殊字符 - "("和 "&"字符

java - Libgdx 无法加载纹理问题

java - Spring & Java Generics - 在抽象 Controller 中获取一项服务的实例

java - 对从文本文件中提取的数据进行排序

java - Java社交网络引擎列表(框架/平台)

Java 密码库偶尔无法启动

java - 外部配置

java - 正则表达式 - 在 `:` 上分割字符串,但不在 if 语句内分割字符串

java - Spring 电子邮件和换行字符