美文网首页pdf电子书下载我爱编程
Java Singleton Design Pattern Ex

Java Singleton Design Pattern Ex

作者: rejoice001 | 来源:发表于2018-08-09 17:07 被阅读18次

    转自:https://www.callicoder.com/java-singleton-design-pattern-example/

    Singleton design pattern is used when you want to have only one instance of a given class.

    It is a creational design pattern wherein we deal with the creation of objects.

    Motivation and Real world examples

    In object-oriented design, It’s very important for some classes to have only one instance. That’s because they represent something unique, something that’s one of its kind.

    Let’s see some real-world examples of Singletons from the Java language to understand what that means -

    java.lang.Runtime: Java provides a Runtime class that represents the current runtime environment in which an application is running. The application can interface with its runtime environment using this class.

    Since the Runtime environment is unique, There should only be one instance of this class.

    java.awt.Desktop: The Desktop class allows Java applications to launch a URI or a file with the applications that are registered on the native Desktop like the user’s default browser, or mail client.

    The native Desktop and the associated applications are one-of-a-kinds. So there must be only one instance of the Desktop class.

    Implementing the Singleton Design Pattern

    How do you ensure that a class has only one instance? Well, there are several ways of doing this in Java. But all of them are based on the following basic ideas:

    Declare a private constructor to prevent others from instantiating the class.

    Create the instance of the class either during class loading in a static field/block, or on-demand in a static method that first checks whether the instance exists or not and creates a new one only if it doesn’t exist.

    Let’s see all the possible solutions with code samples one by one:

    1. Eagerly Initialized Singleton

    This is the simplest approach wherein the instance of the class is created at the time of class loading -

    publicclassEagerSingleton{/** private constructor to prevent others from instantiating this class */privateEagerSingleton(){}/** Create an instance of the class at the time of class loading */privatestaticfinalEagerSingleton instance=newEagerSingleton();/** Provide a global point of access to the instance */publicstaticEagerSingletongetInstance(){returninstance;}}

    The disadvantage of this approach is that the instance is created irrespective of whether it is accessed or not. This is fine if the object is simple and does not hold any system resources. But can have performance implications if it allocates a large amount of system resources and remains unused.

    2. Eagerly Initialized Static Block Singleton

    You can also create the one-off instance of the class in a static block. This works because the static block is executed only once at the time of class loading.

    The advantage with static block initialization is that you can write your initialization logic or handle exceptions.

    publicclassEagerStaticBlockSingleton{privatestaticfinalEagerStaticBlockSingleton instance;/** Don't let anyone else instantiate this class */privateEagerStaticBlockSingleton(){}/** Create the one-and-only instance in a static block */static{try{instance=newEagerStaticBlockSingleton();}catch(Exceptionex){throwex;}}/** Provide a public method to get the instance that we created */publicstaticEagerStaticBlockSingletongetInstance(){returninstance;}}

    Just like the previous solution, the instance is created whether or not it is needed by the application.

    3. Lazily Initialized Singleton

    Lazy initialization means delaying the initialization of something until the first time it is needed.

    In the following implementation, we first check whether the instance is already created or not in the getInstance() method. If the instance is already created, we simply return it, otherwise, we first create the instance and then return it:

    publicclassLazySingleton{privatestaticLazySingleton instance;/** Don't let anyone else instantiate this class */privateLazySingleton(){}/** Lazily create the instance when it is accessed for the first time */publicstaticsynchronizedLazySingletongetInstance(){if(instance==null){instance=newLazySingleton();}returninstance;}}

    Notice the use of synchronized keyword in the getInstance() method. This is needed to prevent race conditions in multi-threaded environments.

    Let’s say that the instance is not created yet, and two threads enter the getInstance() method simultaneously. In that case, the instance==null check will evaluate to true and both the threads will create a new instance of the class.

    The synchronized keyword ensures that only one thread can execute the getInstance() method at a time.

    4. Lazily Initialized Double-Checked Locking Singleton

    The synchronized keyword added to the getInstance() method prevents race conditions, but it also incurs some performance penalty.

    Following is an optimized version of the lazily initialized singleton where - instead of making the entire method synchronized, we create a synchronized block and wrap only the instantiation part inside the synchronized block -

    publicclassLazyDoubleCheckedLockingSingleton{privatestaticvolatileLazyDoubleCheckedLockingSingleton instance;/** private constructor to prevent others from instantiating this class */privateLazyDoubleCheckedLockingSingleton(){}/** Lazily initialize the singleton in a synchronized block */publicstaticLazyDoubleCheckedLockingSingletongetInstance(){if(instance==null){synchronized(LazyDoubleCheckedLockingSingleton.class){// double-checkif(instance==null){instance=newLazyDoubleCheckedLockingSingleton();}}}returninstance;}}

    The above approach is called Double-Checked Locking because we double-check whether the variable is initialized or not inside the synchronized block.

    The double-checking is very important here. Let’s say that two threads T1 and T2 enter the getInstance() method simultaneously. The instance==null check will evaluate to true, so both of them will enter the synchronized block one-by-one. If the double check was not there, both threads would create a new instance.

    Also, notice the use of volatile keyword with the instance variable. This is necessary to prevent compilers from doing their own optimizations and handle the singleton correctly.

    Wikipedia has a great explanation of double-checked locking along with Java code. Check that out here.

    5. Lazily Initialized Inner Class Singleton (Bill Pugh singleton)

    Bill Pugh came up with a very efficient solution to create singletons. It is called Initialization-on-demand holder idiom. In this approach, a static inner class is used to lazily create a singleton instance.

    publicclassLazyInnerClassSingleton{/** private constructor to prevent others from instantiating this class */privateLazyInnerClassSingleton(){}/** This inner class is loaded only after getInstance() is called for the first time. */privatestaticclassSingletonHelper{privatestaticfinalLazyInnerClassSingleton INSTANCE=newLazyInnerClassSingleton();}publicstaticLazyInnerClassSingletongetInstance(){returnSingletonHelper.INSTANCE;}}

    Note that, the inner class is not loaded until the getInstance() method is invoked for the first time. This solution is thread-safe and doesn’t require any synchronization. It is the most efficient approach among all the singleton design pattern implementations.

    6. Enum Singleton

    An Enum is singleton by design. All the enum values are initialized only once at the time of class loading.

    importjava.util.Arrays;/** An Enum value is initialized only once at the time of class loading.

        It is singleton by design and is also thread-safe.

    */enumEnumSingleton{WEEKDAY("Monday","Tuesday","Wednesday","Thursday","Friday"),WEEKEND("Saturday","Sunday");privateString[]days;EnumSingleton(String...days){System.out.println("Initializing enum with "+Arrays.toString(days));this.days=days;}publicString[]getDays(){returnthis.days;}@OverridepublicStringtoString(){return"EnumSingleton{"+"days="+Arrays.toString(days)+'}';}}publicclassEnumSingletonExample{publicstaticvoidmain(String[]args){System.out.println(EnumSingleton.WEEKDAY);System.out.println(EnumSingleton.WEEKEND);}}

    # OutputInitializing enum with[Monday, Tuesday, Wednesday, Thursday, Friday]Initializing enum with[Saturday, Sunday]EnumSingleton{days=[Monday, Tuesday, Wednesday, Thursday, Friday]}EnumSingleton{days=[Saturday, Sunday]}

    The disadvantage of this approach is that it is a bit inflexible compared to other approaches.

    Singletons and Reflection

    Java’s Reflection API is very powerful. You can use Reflection to instantiate a class even if the class’s constructor is private.

    Let’s see it in action:

    importjava.lang.reflect.Constructor;classMySingleton{privatestaticfinalMySingleton instance=newMySingleton();privateMySingleton(){}publicstaticMySingletongetInstance(){returninstance;}}publicclassSingletonAndReflection{publicstaticvoidmain(String[]args){MySingleton singletonInstance=MySingleton.getInstance();MySingleton reflectionInstance=null;try{Constructor[]constructors=MySingleton.class.getDeclaredConstructors();for(Constructor constructor:constructors){constructor.setAccessible(true);reflectionInstance=(MySingleton)constructor.newInstance();}}catch(Exceptionex){thrownewRuntimeException(ex);}System.out.println("singletonInstance hashCode: "+singletonInstance.hashCode());System.out.println("reflectionInstance hashCode: "+reflectionInstance.hashCode());}}

    # OutputsingletonInstance hashCode: 1618212626reflectionInstance hashCode: 947679291

    Notice how we created a new instance of the Singleton using constructor.newInstance(). This destroys the singleton pattern.

    Protection against Reflection

    To protect your singleton class against instantiation via reflection, you can throw an exception from the private constructor if the instance is already created like this -

    classMySingleton{privatestaticfinalMySingleton instance=newMySingleton();privateMySingleton(){// protect against instantiation via reflectionif(instance!=null){thrownewIllegalStateException("Singleton already initialized");}}publicstaticMySingletongetInstance(){returninstance;}}

    You can also use an Enum singleton to guard against reflection. Enums can’t be initialized via reflection. They are a sure shot way of having a single instance no matter what.

    Singletons and Serialization

    We often need to serialize/deserialize objects in Java. Any class that needs to be serialized/deserialized must implement the serializable interface.

    Note that, the de-serialization step always creates a new instance of the class, which destroys the singleton pattern. Here is an example -

    importjava.io.*;classSerializableSingletonimplementsSerializable{privatestaticfinallongserialVersionUID=8806820726158932906L;privatestaticSerializableSingleton instance;privateSerializableSingleton(){}publicstaticsynchronizedSerializableSingletongetInstance(){if(instance==null){instance=newSerializableSingleton();}returninstance;}}publicclassSingletonAndSerialization{publicstaticvoidmain(String[]args){SerializableSingleton instance1=SerializableSingleton.getInstance();try{// Serialize singleton object to a file.ObjectOutput out=newObjectOutputStream(newFileOutputStream("singleton.ser"));out.writeObject(instance1);out.close();// Deserialize singleton object from the fileObjectInput in=newObjectInputStream(newFileInputStream("singleton.ser"));SerializableSingleton instance2=(SerializableSingleton)in.readObject();in.close();System.out.println("instance1 hashCode: "+instance1.hashCode());System.out.println("instance2 hashCode: "+instance2.hashCode());}catch(IOExceptionex){ex.printStackTrace();}catch(ClassNotFoundExceptionex){ex.printStackTrace();}}}

    # Outputinstance1 hashCode: 1348949648instance2 hashCode: 434091818

    Notice how the hashCodes of the original instance and the de-serialized instance are different. There are clearly two instances of our singleton class.

    Protection against Serialization

    To prevent the de-serialization process from creating a new instance, you can implement the readResolve() method in the singleton class. It is invoked when the object is de-serialized.

    In the readResolve() method, you must return the existing instance -

    classSerializableSingletonimplementsSerializable{privatestaticfinallongserialVersionUID=8806820726158932906L;privatestaticSerializableSingleton instance;privateSerializableSingleton(){}publicstaticsynchronizedSerializableSingletongetInstance(){if(instance==null){instance=newSerializableSingleton();}returninstance;}// implement readResolve method to return the existing instanceprotectedObjectreadResolve(){returninstance;}}

    Conclusion

    In this article, you learned what is a singleton design pattern and when should you use it. You learned various ways of implementing the singleton design pattern and understood the pros and cons of every approach.

    Thanks for reading. See you in the next post.

    相关文章

      网友评论

        本文标题:Java Singleton Design Pattern Ex

        本文链接:https://www.haomeiwen.com/subject/ejecbftx.html