WHEN is a singleton not a singleton?
Avoid Multiple Singleton Instances by Keeping Tips in Mind
Purposely reloaded singleton classes Classes are reloaded not only after class garbage-collection; they can also be reloaded at Java programs' request The servlet specifications allow servlet engines to do that at any time When the servlet engine decides to unload a servlet class,.. it calls destroy (), then discards the servlet class;. later, the servlet engine can reload the servlet class, instantiate the servlet object, and initialize it by calling init () in practice, the process of unloading and reloading may occur in a Servlet Engine WHEN A Servlet Class or Jsp Changes.
Like The Previous Two Cases, The Present Case Involves Newly Load Classes. Here, However, Classes Are Ditched on Purpose, While A New Copy of The Class Loads.
Depending on the servlet engine, when an old servlet class is discarded, the associated classes might not be, even if they have changed. So if a servlet gets a reference to a singleton object, you may find that there is one singleton object associated with The old servlet class and one associated with the new.
AS Servlet Engines Differ In Their Class-Reloading Policies, The Singleton Behavior Is Unpredictable Unless Issue's Class-Loading Mechanisms Work.
Similar problems can occur if you hold a reference from another object to a servlet and some chain of references keeps that object from the garbage collector. Then, when the servlet class should be discarded, it can not be, and you may find the servlet class loaded TWICE IN THE VM.
Multiple instances resulting from incorrect synchronization One of the common singleton implementations uses lazy initialization of the one instance. That means that the instance is not created when the class loads, but rather when it is first used. (See Listing 2.) A common mistake With Implementation is to Neglect Synchronization, Which Can Lead to Multiple Instances of The Singleton Class. (See Listing 3.) Listing 3
// error, no synchronization on methodpublic static mysingleton getinstance () {instance == null) {_instance = new mysingleton ();} return_instance;
Two singletons will be created if the constructor runs and simultaneously another thread calls the method. Thread-safe code is particularly important in singletons, since that Design Pattern is meant to give the user a single point of access that hides the complexities of the implementation, Including Multithreading Issues.
Multiple INSTANCES Can Be CREATED EVEN IF you add a synchronized (this) block to the constructor call, AS in Listing 4:
Listing 4
// Also an error, synchronization does not prevent // two calls of constructor.public static MySingleton getInstance () {if (_instance == null) {synchronized (MySingleton.class) {_instance = new MySingleton ();}} return _instance }
In The Correct Solution, Seen in Listing 5, Make GetInstance () A SYNCHRONED METHOD:
Listing 5
// Correct SolutionPublic Static Synchronized Mysingleton getInstance () {//...........?
Double-Checked Locking is Another Common Solution But, Unfortunately, It Does NOT WORK (See Listing 6).
Listing 6
// Double-checked locking - do not usepublic static MySingleton getInstance () {if (_instance == null) {synchronized (MySingleton.class) {if (_instance == null) {_instance = new MySingleton ();}} }} In this situation, we intend to avoid the expense of grabbing the lock of the singleton class every time the method is called. The lock is grabbed only if the singleton instance does not exist, and then the existence of the instance is checked again IN Case Another Thread Passed The First Check An Instant Before The Current Thread.
Unfortunately, double-checked locking causes problems. To wit, compiler optimizations can make the assignment of the new singleton object before all its fields are initialized. (See "Double-checked locking is broken" in Resources.) The only practical solution is to Synchronize the getInstance () Method (As in Listing 2).
Multiple singletons arising when someone has subclassed your singleton The Singleton design pattern is meant to give you control over access to the singleton class While I have mostly discussed the control of instantiation, other code can access your class another way:. By subclassing it.
The uniqueness of the class can not be imposed as a compile-time constraint on the subclass unless you use a private constructor. If you want to allow subclassing, for example, you might make the constructor protected. A subclass could expose a public constructor then, Allowing Anyone to make instances.
Multiple singletons created by a factory specially asked to create multiple objects One of the strengths of the Singleton design pattern, as opposed to static methods, is that if you change your mind and want more than one, the singleton class can be easily altered.For example, most servlets run as singletons in their servlet engines. Since that can cause threading problems, in one alternative (not recommended, but available) the servlet can implement SingleThreadModel. in that case, the servlet engine may, if necessary, create more than One servlet instance. if you are used to the More Common Singleton Servlets, You May Forget That Some Servlets CAN Occur In Multiple Instances.
Copies of a singleton object that has undergone serialization and deserialization If you have a serialized object and deserialize it twice in different ObjectOutputStreams, or with calls ObjectOutputStream.reset () between deserializations, you get two distinct objects, not two references to the same object.
Likewise, when you serialize an object with an ObjectOutputStream, the closure of its graph of references serializes with it. If the ObjectOutputStream closes and a new one opens, or if reset () is called on the ObjectOutputStream, the graph of references breaks and a New One is started. so if you Serialize One Singleton Twice, The Two Serialized Objects Take on Separate Identities.
The object serialization of the java.io package is not the only way to serialize Java objects. New mechanisms of object serialization with XML have been developed, including those associated with SOAP, WDDX, and KOALA, among others. With all those mechanisms, a reconstituted object loses its referential identity, and you have to consider carefully whether your singleton is still a singleton.Multiple singletons caused by problems in a factory in some implementations of creational design patterns in the factory family, the factory is a singleton structured to create an Instance of Against Multiple The Factory Will Ensure................
IF you Accidentally Have More One Factory Object for One of the Reason Above, You Will Still Have Two of The create Objects, Even IF Each Factory Object Is Built Correctly.
Conclusion Singletons are a useful way to control access to a class, making sure that only one instance can exist. In some none-too-uncommon circumstances, however, multiple instances can occur, even in a class coded as a singleton. By being aware Of The Possibility, You Can Be Sure That Your Singleton Really Is A Singleton.
In this Article, I'VE Presented Some Ways That The Multiple Singleton Might Emerge. If'VE Discovered Any Others, I'd Be Interested In Hearing About Them.
Acknowledgement My Thanks to Alexander Radzin for Valuable Comments on this article.