Java design Pattern-Singleton mode (creation mode)

Source: Internet
Author: User
Tags visibility volatile

Overview

?? The singleton mode guarantees that for each class loader, there is only one instance of a class and provides global access. It is an object-creation pattern. The following scenarios are mainly used for Singleton mode:

    • The system requires only one instance object, such as providing a unique serial number generator
    • A single instance of the client invocation class allows only one public access point, except for that public access point, which cannot be accessed by other means

?? One disadvantage of the singleton pattern is that in a distributed environment, if Bugs is generated because of singleton mode, it is difficult to debug to find the problem, because debugging under a single ClassLoader does not cause problems.

Implementation method

?? In general, there are five ways to implement enumerations: a hungry man, lazy, double lock, Static inner class, enumeration, and here I'll take these five ways into three parts.

A hungry man-load
publicclass Singleton {    //私有构造器,所以无法实例化类对象    privateSingleton() {}    //类静态实例域    privatestaticfinalnewSingleton();    //返回类实例    publicstaticgetInstance() {        return INSTANCE;    }}

The direct initialization of a static instance guarantees thread safety, but this is not lazy loading, and the singleton is initialized at the outset and cannot be initialized when we need it.

Lazy-loading
//实例在这个方法第一次被调用的时候进行初始化publicstaticsynchronizedgetInstance() {    ifnull) {        newSingleton();    }    return instance;}

getInstance()Method is set to synchronized ensure thread safety, but it is not efficient because only one thread can access the method at any time, and the synchronization operation needs to be required only when it is first called.

An improvement of this method is the use of a double lock test.

 Public classthreadsafedoublechecklocking {Private Static volatileThreadsafedoublechecklocking instance;Private threadsafedoublechecklocking() {} Public StaticThreadsafedoublechecklockinggetinstance() {//local variable can improve performance by 25%, this local variable ensures that instance is only read once initialized        //"Effective Java 2nd Edition" P250 pagethreadsafedoublechecklocking result = instance;//Check if the instance has not been initialized        if(Result = =NULL) {//is not initialized, but it is not possible to determine whether another thread has initialized it at this time, so adding an object lock for mutual exclusion            synchronized(threadsafedoublechecklocking.class) {//Once again assign the instance to the local variable for checking because it is possible for other threads to initialize the instance when the current thread is blockedresult = instance;if(Result = =NULL) {//is not initialized at this time, the initialization here can ensure thread safetyInstance = result =New threadsafedoublechecklocking(); }            }        }returnResult }}

The double lock test above uses an optimization method proposed by the effective Java version 2nd, and it is also worth mentioning that it instance is important for the domain to be declared volatile . When a variable is defined volatile , it has two characteristics, the first is to ensure that the variable to all threads of visibility, "visibility" refers to when a thread modifies the value of this variable, The new value is immediately known to other threads (note that operations based on volatile variables are not safe under concurrent programming, for example: Suppose that a volatile-modified field is self-increasing, and the increment operation is not an atomic operation. Then the second thread might read to the domain during the reading of the old value and write back the new value, causing the second thread to see the same value as before the first thread did not increment, to see in more detail the 2nd edition of Java Virtual Machine P366 special rules based on volatile variables) The second is to prohibit order reordering optimization.
At the time of initialization instance = result = new ThreadSafeDoubleCheckLocking() , the JVM did roughly three things:

    • 1. Allocating memory to instance
    • 2. Call the constructor to initialize
    • 3.instance object points to allocated memory

Not declared as volatile , after the instruction is reordered, the order of possible execution is 1-3-2, when thread one executes to 3 this step, not yet executed step 2 (instance non-null, but uninitialized), then for thread two, at this time instance is detected is not NULL, directly returned instance, there will be an error. One point to note is that JDK 1.5 is not volatile really useful until after 1.5, so it is still not guaranteed to be secure until you see the "double-checked Locking is broken" Declaration.

Another lazy way to load is by using static inner classes:

public   Initializingondemandholderidiom {private   () {} public  static  Initializingondemandholderidiom getinstance  () {return  Helperholde    R.instance ; } private  static  class  Helperholder {private  static  final  Initializingondemandholderidiom INSTANCE = new  initializingondeman    Dholderidiom  (); }}

This approach is thread-safe and lazy to load. HelperHolderis private, except that getInstance() there is no way to access it. This approach does not need to rely on other language features (volatile,synchronized), nor does it depend on JDK versions.

Enumeration

The effective Java version 2nd P15 A new way to implement a singleton, using enumerations to implement a single case. Enumeration types are part of the new features in Java 5, so enumerations implemented in this way require at least JDK version 1.5 and above. The enumeration itself guarantees thread safety and provides a serialization mechanism, so this approach is extremely concise to write.

public enum Singleton {    INSTANCE;}

Of course, there are some drawbacks to using enumerations to implement singleton patterns, and you can see the stackoverflow discussion.

Typical usage scenarios
    • Log Record class
    • Managing connections to the database
    • File Management System
Specific examples

Java.lang.runtime#getruntime ()
Java.awt.desktop#getdesktop ()
Java.lang.system#getsecuritymanager ()

Resources
    • Java-design-patterns
    • "Effective Java 2nd Edition"

Java design Pattern-Singleton mode (creation mode)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.