When to use(Singleton mode):
When creating objects such as thread pools, caches, and so on, we can use a singleton pattern to avoid wasting resources. But if you want to store global data such as product prices, the singleton pattern becomes a reverse pattern, and you should consider replacing it with other methods.
Note: The singleton has become a reverse pattern here, and we can avoid it with the following techniques:
1. Injection of dependency;
2. Use the factory design mode;
3. Use Enum class and so on ();
Enum Singleton-the preferred approach public
enum Mysingleton {
INSTANCE;
}
A single example design pattern in cluster environment
In a multi-JVM environment, each JVM has its own copy of the Singleton object, which can cause many problems, especially in environments where access to resources requires a restricted and locking cluster.
Many technologies (JMS, DB, custom APIs, third-party tools) can be used to implement cross-JVM clusters, but these technologies will affect system business logic.
Application servers also provide some level of API to avoid such problems. Terracotta, Oracle Coherence is a good choice. They are able to provide an object that replicates memory across the JVM, you can use the singleton view that it provides, or use a cluster cache provider, such as Swarm cache or JBoss Treecache, where the singleton and cluster are built in.
In addition, there is a product called JGroups-it uses mulch-cast communication (TCP/UDP). It allows a set of applications (JVM-based) to communicate with each other to maintain synchronization.
JBoss has a singleton service (based on MBeans), which means it can solve this problem (a singleton in the cluster). Click here and here.
Weblogic also has the concept of a singleton service-there is only one instance in the cluster, and the other server accesses the instance as a client.
WebSphere provides a single-instance cross-cluster concept in the WebSphere XD version, using ObjectGrid as the (singleton) separation tool.
Original link: http://javaarchitectforum.com/2013/02/19/singleton-design-pattern-with-example/.