How are static objects handled during clustering?

Static objects are initialized only once. Single classes are created only once. If we use singleton in a cluster, then it will create several singleton instances in the clusters. So what happens to a static object in a cluster environment? Why is this object not initialized on other servers in the cluster? or why the state of objects does not change?

+4
source share
3 answers

Static objects are always in the ClassLoader area (in most cases on the JVM) and are not considered in clustering. If you need a singleton, you must tell the container to create it. It depends on the nature of your Singleton if it should exist only once per cluster or once per JVM or once per Classloader.

+3
source

Each node in the cluster runs in a separate JVM, so each JVM (cluster node) will have its own Singleton. If you consider the cluster as a JVM system, then it is true that the number of Singleton instances in the cluster is equal to the number of nodes.

A single cluster-wide singleton cannot be implemented using regular Java classes. You may need one (non-clustered) server instance that provides singleton.

+3
source

Singlets are not even reliable in a single process. You can load the same class through several class loaders and end up with multiple "singleton" objects.

Singleton is an anti-pattern for some reason - avoid it.

In a cluster, things are even worse, since all nodes must coordinate the decision where the singleton will be located. This is vulnerable to network separation, so it is untenable. The Brewer CAP Theorem will give you some idea about this.

+2
source

All Articles