20
Java Singleton Design Pattern Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM. The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object. One such scenario where it might prove useful is when we develop the help Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications. Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application. Implementing Singleton Pattern To implement this design pattern we need to consider the following 4 steps: <br /><font size=-1> Step 1: Provide a default Private constructor public class SingletonObjectDemo { // Note that the constructor is private private SingletonObjectDemo() { // Optional Code } }

COREJAVA@ADVACEDJAVA

  • Upload
    phani

  • View
    214

  • Download
    0

Embed Size (px)

DESCRIPTION

java

Citation preview

Java Singleton Design PatternJava has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JV.The class!s default constructor is made private, "hich prevents the direct instantiation of the object by others (#ther $lasses). % static modifier is applied to the instance method that returns the object as it then ma&es this method a class level method that can be accessed "ithout creatingan object.#ne such scenario "here it might prove useful is "hen "e develop the help odule in a project. Java 'elp is an e(tensible, platform)independent help system that enables authors and developers to incorporate online help into applications.Singletons can be used to create a $onnection Pool. *f programmers create a ne" connection object in every class that re+uires it, then its clear "aste of resources. *n this scenario by using a singleton connection class "e can maintain a single connection object "hich can be used throughout the application.Implementing Singleton PatternTo implement this design pattern "e need to consider the follo"ing , steps-.br /0.font si1e2)30Step 3- Provide a default Private constructor public class SingletonObjectDemo {// Note that the constructor is privateprivate SingletonObjectDemo() {// Optional Code}}Step 4- $reate a ethod for getting the reference to the Singleton #bjectpublic class SingletonObjectDemo {private static SingletonObject singletonObject;// Note that the constructor is privateprivate SingletonObjectDemo() {// Optional Code}public static SingletonObjectDemo getSingletonObject() {i (singletonObject !! null) {singletonObject ! ne" SingletonObjectDemo();}return singletonObject;}}5e "rite a public static getter or access method to get the instance of the Singleton #bject at runtime. 6irst time the object is created inside this method as it is null. Subse+uent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.Step 7- a&e the %ccess method Synchroni1ed to prevent Thread Problems.public static synchroni1ed Singleton#bject8emo getSingleton#bject()*t could happen that the access method may be called t"ice from 4 different classes at the same time and hence more than one object being created. This could violate the design patter principle.*n order to prevent the simultaneous invocation of the getter method by 4 threads or classes simultaneously "e add the synchroni1ed &ey"ord to the method declarationStep ,- #verride the #bject clone method to prevent cloning5e can still be able to create a copy of the #bject by cloning it using the #bject!s clone method. This can be done as sho"n belo"Singleton#bject8emo cloned#bject 2 (Singleton#bject8emo) obj.clone()9This again violates the Singleton 8esign Pattern!s objective. So to deal "ith this "e need to override the #bject!s clone method "hich thro"s a $lone:otSupported;(ception e(ception.public #bject clone() thro"s $lone:otSupported;(ception s purpose is to control object creation, limiting the number to one but allo"ing the fle(ibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton "ill occur only once per class, just li&e static fields.Singletons often control access to resources such as database connections or soc&ets. 6or e(ample, if you have a license for only one connection for your database or your J8?$ driver has trouble "ith multithreading, the Singleton ma&es sure that only one connection is made or that only one thread can access the connection at a time. *f you add database connections or use aJ8?$ driver that allo"s multithreading, the Singleton can be easily adjusted to allo" more connections. oreover, Singletons can be stateful9 in this case, their role is to serve as a uni+ue repository of state. *f you are implementing a counter that needs to give out se+uential and uni+ue numbers (such as the machine that gives out numbers in the deli), the counter needs to be globally uni+ue. The Singleton can hold the number and synchroni1e access9 if later you "ant to hold counters in a database for persistence, you can change the private implementation of the Singleton "ithout changing the interface. #n the other hand, Singletons can also be stateless, providing utility functions that need no more information than their parameters. *n that case, there is no need to instantiate multiple objects that have no reason for their e(istence, and so a Singleton is appropriate. The Singleton should not be seen as "ay to implement global variables in the Java programming language9 rather, along the lines of the factory design patterns, the Singleton lets you encapsulateand control the creation process by ma&ing sure that certain prere+uisites are fulfilled or by creating the object la1ily on demand. 'o"ever, in certain situations, t"o or more Singletons can mysteriously materiali1e, disrupting the very guarantees that the Singleton is meant to provide. 6or e(ample, if your Singleton 1rame is meant as a global user interface for your application and t"o are created, your application "ill have t"o 1rames on the screen )) +uite confusing for the user. 6urther, if t"o counters are created"here one "as intended, then clients re+uesting numbers "ill not get the desired se+uence 3, 4, 7... but rather a multiple se+uence such as 3, 3, 4, 4, 7, 7, 7.... %dditionally, if several instances ofa database)connection Singleton are created, you might start receiving S2.()ceptions complaining about @too many database connections.@ *n this article, *>ll describe those phenomena and ho" to avoid them. %fter discussing ho" to implement the Singleton, *>ll go over the sometimes surprising causes for the phenomena one by one, sho"ing you ho" they occur and ho" you can avoid ma&ing those mista&es. * hope that in the process you "ill learn about classloading, multithreading, distributed systems, 8esign Patterns, and other interesting topics, as * did. Implementing SingletonsThere are a fe" "ays to implement Singletons. %lthough you can get Singleton)li&e behavior "ith static fields and methods Afor e(ample, java&lang&3ath&sin(double)B, you gain more fle(ibility by creating an instance. 5ith Singletons implemented as single instances instead of static class members, you can initiali1e the Singleton la1ily, creating it only "hen it is first used. Ci&e"ise, "ith a Singleton implemented as single instance, you leave open the possibility of altering the class to create more instances in the future. 5ith some implementations of the Singleton, you allo" "riters of subclasses to override methods polymorphically, something not possible "ith static methods. ost commonly, you implement a Singleton in Java by having a single instance of the class as a static field. Dou can create that instance at class)loading time by assigning a ne"ly created objectto the static field in the field declaration, as seen in Cisting 3. Listing 1public class 3%Singleton { private static 3%Singleton 4instance ! ne" 3%Singleton(); private 3%Singleton() { // construct object & & & } public static 3%Singleton get0nstance() { return 4instance; } // 5emainder o class deinition & & & %lternatively, you can instantiate it la1ily, on first demand, as seen in Cisting 4. Dou &eep the constructor private to prevent instantiation by outside callers. Listing 2public class 3%Singleton { private static 3%Singleton 4instance; private 3%Singleton() { // construct object & & & } // 1or la'% initiali'ation public static s%nchroni'ed 3%Singleton get0nstance() { i (4instance!!null) { 4instance ! ne" 3%Singleton(); } return 4instance; } // 5emainder o class deinition & & & } ?oth Singleton implementations do not allo" convenient subclassing, since get0nstance(), being static, cannot be overridden polymorphically. #ther implementations prove more fle(ible. 5hile * don>t have the space to describe alternative implementations in detail, here are a couple of possibilities- #f you implement a fa$tory $lass %ith a method that returns the Singleton instan$e& you allo% yourself 'exi(ility in the runtime $lass of the return value&%hi$h $an (e either 3%Singleton or a su($lass thereof) *ou may have to ma+e the $onstru$tor nonprivate to ma+e that %or+) *ou $an have a Singleton1actor% $lass %ith a glo(ally a$$essi(le map of $lassnames or Class o(,e$ts to Singleton instan$es) -gain& the runtime type of the instan$es $an (e either the type indi$ated (y the $lass name or a su($lass& and the $onstru$tor %ill not (e private)6or other possible implementations, see @*mplementing the Singleton Pattern in Java@ in Eesources. %s * discuss the Singleton, &eep the above implementations in mind, although many of those phenomena can occur for any implementation of the Singleton. :o" that "e>ve loo&ed briefly at implementation, let>s turn to the heart of this article- ho" t"o Singletons can e(ist simultaneously. Multiple Singletons in Two or More Virtual Machines5hen copies of the Singleton class run in multiple Vs, an instance is created for each machine.That each V can hold its o"n Singleton might seem obvious but, in distributed systems such asthose using ;J?s, Jini, and E*, it>s not so simple. Since intermediate layers can hide the distributed technologies, to tell "here an object is really instantiated may be difficult. 6or e(ample, only the ;J? container decides ho" and "hen to create ;J? objects or to recycle e(isting ones. The ;J? may e(ist in a different V from the code that calls it. oreover, a single;J? can be instantiated simultaneously in several Vs. 6or a stateless session bean, multiple calls to "hat appears, to your code, to be one instance could actually be calls to different instances on different Vs. ;ven an entity ;J? can be saved through a persistence mechanism bet"een calls, so that you have no idea "hat instance ans"ers your method calls. (The primary &ey that is part of the entity bean spec is needed precisely because referential identity is of no usein identifying the bean.) The ;J? containers> ability to spread the identity of a single ;J? instance across multiple Vs causes confusion if you try to "rite a Singleton in the conte(t of an ;J?. The instance fields of the Singleton "ill not be globally uni+ue. ?ecause several Vs are involved for "hat appears to be the same object, several Singleton objects might be brought into e(istence. Systems based on distributed technologies such as ;J?, E*, 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 ;J?s, since resource management is the role of the ;J? container. 'o"ever, in other distributed systems, Singleton objects that control resources may be used on the understanding that they are not uni+ue in the distributed system, just in the particular V. Multiple Singletons Simultaneously Loaded by Diferent Class Loaders5hen t"o class loaders load a class, you actually have t"o copies of the class, and each one can have its o"n Singleton instance. That is particularly relevant in servlets running in certain servletengines (iPlanet for e(ample), "here each servlet by default uses its o"n class loader. T"o different servlets accessing a joint Singleton "ill, in fact, get t"o different objects. ultiple class loaders occur more commonly than you might thin&. 5hen bro"sers load classes from the net"or& for use by applets, they use a separate class loader for each server address. Similarly, Jini and E* systems may use a separate class loader for the different code bases from"hich they do"nload class files. *f your o"n system uses custom class loaders, all the same issues may arise. *f loaded by different class loaders, t"o classes "ith the same name, even the same pac&age name, are treated as distinct )) even if, in fact, they are byte)for)byte the same class. The differentclass loaders represent different namespaces that distinguish classes (even though the classes> names are the same), so that the t"o 3%Singleton classes are in fact distinct. (See @$lass Coaders as a :amespace echanism@ in Eesources.) Since t"o Singleton objects belong to t"o classes of the same name, it "ill appear at first glance that there are t"o Singleton objects of the same class. Singleton Classes Destroyed by Garbage Collection, then eloaded5hen a Singleton class is garbage)collected and then reloaded, a ne" Singleton instance is created. %ny class can be garbage)collected "hen no other object holds reference to the class or its instances. *f no object holds a reference to the Singleton object, then the Singleton class may disappear, later to be reloaded "hen the Singleton is again needed. *n that case, a ne" Singleton object "ill be created. %ny static or instance fields saved for the object "ill be lost and reinitiali1ed. This problems e(ists in older Java Virtual achines3. J8F 3.4 Vs, in particular, conform to a ne"er class garbage collection model that forbids any class in a given classloader to be collected until all are unreferenced (see Programming Java threads in the real "orld, Part G@ in Eesources).Dou can avoid class garbage collection in the older Vs by holding a reference to the Singleton class or object in some other object that persists for the program>s life. Dou can also set your V to have no class garbage collection (67noclassgc on the JE; 3.7, or 6noclassgc on the *? JV). Feep in mind that if you have a long)running program that fre+uently reloads classes (perhaps through special class loaders such as the remote class loaders), you have to consider "hether that could cause a problematic buildup of garbage classes in the V. !urposely eloaded Singleton Classes$lasses are reloaded not only after class garbage)collection9 they can also be reloaded at Java programs> re+uest. The servlet specifications allo" servlet engines to do that at any time. 5hen the servlet engine decides to unload a servlet class, it calls destro%(), then discards the servlet class9 later, the servlet engine can reload the servlet class, instantiate the servlet object, and initiali1e it by calling init(). *n practice, the process of unloading and reloading may occur in a servlet engine "hen a servlet class or JSP changes. Ci&e the previous t"o cases, the present case involves ne"ly loaded classes. 'ere, ho"ever, classes are ditched on purpose, "hile a ne" copy of the class loads. 8epending on the servlet engine, "hen 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 "ith the old servlet class and one associated "ith the ne". %s servlet engines differ in their class)reloading policies, the Singleton behavior is unpredictable unless you understand ho" your servlet engine>s class)loading mechanisms "or&. Similar problems can occur if you hold a reference from another object to a servlet and some chain of references &eeps that object from the garbage collector. Then, "hen the servlet class should be discarded, it cannot be, and you may find the servlet class loaded t"ice in the V. Multiple Instances esulting "rom Incorrect Synchroni#ation#ne of the common Singleton implementations uses la1y initiali1ation of the one instance. That means that the instance is not created "hen the class loads, but rather "hen it is first used. (See Cisting 4.) % common mista&e "ith that implementation is to neglect synchroni1ation, "hich can lead to multiple instances of the singleton class. (See Cisting 7.) Listing 3// error8 no s%nchroni'ation on method public static 3%Singleton get0nstance() { i (4instance!!null) { 4instance ! ne" 3%Singleton(); } return 4instance; } T"o Singletons "ill be created if the constructor runs and simultaneously another thread calls themethod. Thread)safe code is particularly important in Singletons, since that 8esign Pattern is meant to give the user a single point of access that hides the comple(ities of the implementation, including multithreading issues. ultiple instances can be created even if you add a s%nchroni'ed(this) bloc& to the constructor call, as in Cisting ,- Listing 4// $lso an error8 s%nchroni'ation does not prevent // t"o calls o constructor& public static 3%Singleton get0nstance() { i (4instance!!null) { s%nchroni'ed (3%Singleton&class) { 4instance ! ne" 3%Singleton(); } } return 4instance; } *n the correct solution, seen in Cisting H, ma&e get0nstance() a synchroni1ed method- Listing 5// correct solution public static s%nchroni'ed 3%Singleton get0nstance() { // & & & continue as in .isting 9 8ouble)chec&ed loc&ing is another common solution but, unfortunately, it does not "or& (see Cisting I). Listing 6// Double6chec:ed loc:ing 66 don;t use public static 3%Singleton get0nstance() { i (4instance!!null) { s%nchroni'ed (3%Singleton&class) { i (4instance!!null) { 4instance ! ne" 3%Singleton(); } } } } *n this situation, "e intend to avoid the e(pense of grabbing the loc& of the Singleton class every time the method is called. The loc& is grabbed only if the Singleton instance does not e(ist, and then the e(istence of the instance is chec&ed again in case another thread passed the first chec& an instant before the current thread. Jnfortunately, double)chec&ed loc&ing causes problems. To "it, compiler optimi1ations can ma&e the assignment of the ne" Singleton object before all its fields are initiali1ed. (See @8ouble)chec&ed loc&ing is bro&en@ in Eesources.) The only practical solution is to synchroni1e the get0nstance() method (as in Cisting 4). Multiple Singletons $rising when Someone has Subclassed your SingletonThe Singleton 8esign Pattern is meant to give you control over access to the Singleton class. 5hile * have mostly discussed the control of instantiation, other code can access your class another "ay- by subclassing it. The uni+ueness of the class cannot be imposed as a compile)time constraint on the subclass unless you use a private constructor. *f you "ant to allo" subclassing, for e(ample, you might ma&e the constructor protected. % subclass could then e(pose a public constructor, allo"ing anyone to ma&e instances. Since an instance of a subclass is an instance of your superclass, you could find multiple instances of the Singleton. Multiple Singletons Created by a %actory Specially $s&ed to Create Multiple 'b(ects#ne of the strengths of the Singleton design pattern, as opposed to static methods, is that if you change your mind and "ant more than one, the Singleton class can be easily altered. 6or e(ample, 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 Singleve discovered any others, *>d be interested in hearing about them. Java Singleton design pattern tutorial. ?y Viral Patel on January 3,, 4LLM Java, Tutorial Java Singleton design pattern is one of the design pattern that governs the instantiation of an object in Java. This design pattern suggest that only one instance of a Singleton object is created by the JV. This pattern is useful "hen e(actly one object is needed to coordinate actions acrossthe system. %lso it can be generali1ed to restrict the objects to certain number of instances li&e say H objects only.Eelated- 6ree 8esign Pattern Eeference $ardClass diagram o Singleton !lass6ollo"ing is the class diagram of a singleton class. The constructor is &ept private to avoid normal instantiation of objects and all the instantiations are done only through get*nstance() method."ow t#e Singleton pattern wor$s%6ollo"ing is the source of simple class that follo"s singleton pattern.NL3L4L7L,LHLILGLOLM3L333437public class SimpleSingleton {private static SimpleSingleton 0NS