聚类时如何处理静态对象?
静态对象仅初始化一次。 Singleton 类仅实例化一次。如果我们在集群中使用单例,那么它将在集群中创建多个单例实例。 那么静态对象在集群环境中会发生什么呢? 为什么这个对象没有在其他集群服务器中初始化?或者为什么对象状态没有改变?
Static objects are initialized only once. Singleton classes are instantiated only once. If we use a singleton in a cluster then it will create multiple instances of singleton in the clusters.
So what happens to the static object in a cluster environment?
Why this object is not initialized in other cluster servers? or why the objects state doesn't change?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
静态对象始终位于类加载器的范围内(大多数情况下是每个 JVM),并且在集群中不被考虑。如果你需要一个单例,你必须告诉容器创建一个。
如果每个集群只存在一个,或者每个 JVM 或每个类加载器只存在一个,这取决于单例的性质。
Static Objects are always in the scope of the ClassLoader (in most cases per JVM) and are not regarded in clustering. If you need a Singleton you have to tell the container to create one.
It depends on the nature of your Singleton if it should exist only one per Cluster or once per JVM or once per Classloader.
集群中的每个节点都在单独的 JVM 中运行 - 因此每个 JVM(集群节点)都将拥有自己的 Singleton。如果将集群视为一个 JVM 系统,那么集群中 Singleton 实例的数量确实等于节点数量。
集群范围的 Singleton 不能用普通的 Java 类来实现。您可能需要提供单例的单个(非集群)服务器实例。
Each node in a cluster runs in a separate JVM - so each JVM (cluster node) will have it's own Singleton. If you look at the cluster as a system of JVMs, then it is true that the number of instances of a Singleton in the cluster is equal to the number of nodes.
A cluster wide Singleton can not be implemented with normal Java classes. You may need a single (un-clustered) server instances that provides the singleton.
单例在单个进程中甚至都不可靠。您可以通过多个类加载器加载同一个类,并最终得到多个“单例”对象。
单例是一种反模式是有原因的 - 避免它。
在集群中情况更糟,因为所有节点必须协调来决定单例的位置。这很容易受到网络分区的影响,因此是站不住脚的。 Brewer 的CAP 定理将为您提供一些相关背景知识。
Singletons aren't even reliable within a single process. You can load the same class via multiple classloaders and end up with multiple 'singleton' objects.
Singleton is an anti-pattern for a reason - avoid it.
The case is even worse in a cluster since all nodes must coordinate to decide where the singleton will be located. This is vulnerable to network partitioning so it's untenable. Brewer's CAP Theorem will give you some background on this.