Singleton single-Case mode

Source: Internet
Author: User

First, the intention

Ensure that a class has only one instance and provides a global access point to access it.

How can we guarantee that there is only one instance of a class and that this instance is easy to access?

If you assign an object to a Java static variable, you must create a good object at the beginning of the program. In case this object is very resource-intensive, and the program in the implementation of the process has not been used to it, not to form a waste?

A better approach is to have the class itself responsible for preserving its only instance. This class guarantees that no other instance can be created (by intercepting a request to create a new object), and that it can provide a way to access the instance.

This is the S i n g l e t o n mode, and we can create objects when needed. in a computer system, the driver objects of the thread pool, cache, log Object, dialog box, printer, and video card are often designed as singleton.

The singleton pattern is to make sure that the class has only one object in memory, that the instance must be created automatically, and that the provider is provided externally.

Advantage there is only one object in the system memory, so the system resources can be saved, and for some object singleton patterns that need to be created and destroyed frequently, the performance of the system can be improved.

The disadvantage has no abstraction layer, so the extension is difficult. Too heavy a duty to violate a single duty in a certain procedure

Second, the realization of the singleton pattern

The first type: lazy, thread insecure

1  Public classLazynotsecurtysingleton {2  3     //use static variables to record unique instances of the Singleton class4     Private StaticLazynotsecurtysingleton instance;5  6     //private constructs to ensure access only from within the class7     PrivateLazynotsecurtysingleton () {8     }9  Ten     //returns an instance of this class, thread synchronization problem One      Public StaticLazynotsecurtysingleton getinstance () { A         if(Instance = =NULL) { -Instance =NewLazynotsecurtysingleton (); -         } the         returninstance; -     } -}

Singleton by restricting the construction method to private to prevent the class from being instantiated externally, theunique instance of Singleton can only be accessed through the getinstance () method within the same virtual machine scope. (In fact, the Java reflection mechanism is the ability to instantiate a class constructed as private, which basically invalidates all Java Singleton implementations.) This issue is not discussed here, and it is deceiving to assume that the reflection mechanism does not exist. )

However, the above implementations do not take into account thread safety issues. Thread safety refers to the idea that if your code is in a process where multiple threads are running concurrently, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe. Alternatively, a class or program provides an interface that is atomic to a thread, or that a switch between multiple threads does not cause the execution of the interface to be ambiguity, that is , we do not have to consider the problem of synchronization. Obviously the above implementations do not meet the requirements of thread safety, and many singleton instances are likely to occur in concurrent environments .

The second type: Lazy Thread safety

1  Public classLazysecurtysingleton {2     3     Private StaticLazysecurtysingleton instance;4     /**5 * Private constructor to ensure that the class cannot be instantiated outside of the class6      */7     PrivateLazysecurtysingleton () {8     }9  Ten     /** One * Synchronized keyword resolves synchronization issues for multiple threads A      */ -      Public Staticsynchronized Lazysecurtysingleton getinstance () { -         if(Instance = =NULL) { theInstance =NewLazysecurtysingleton (); -         } -         returninstance; -     } +   -}

The synchronization provided by the Synchronized keyword in the static factory method is necessary, otherwise it is not ensured that the same instance is always obtained when multiple threads access the method at the same time. However, we also see that in all code paths, although the instance variable needs to be instantiated only for the first reference , the synchronized synchronization mechanism requires that all code execution paths must first acquire the class lock. When concurrent access is low, the effect is not significant, but when concurrent traffic increases, it can become a bottleneck for concurrent access.

The Third kind: a Hungry man type

 Public classEagersingleton {//Private Class-member constants    Private StaticFinal Eagersingleton SINGLETON =NewEagersingleton (); //private default constructor method, this class cannot be inherited    PrivateEagersingleton () {}//Static Factory Method     Public StaticEagersingleton getinstance () {returnSINGLETON; }  } 

In this way, we rely on the JVM to create a unique instance of the class as soon as the class is loaded, avoiding thread-safety issues. However,instance is instantiated when the class is loaded and does not achieve the effect of lazy loading .

This is how the runtime class in Java is used

1 /*2 * Runtime: Each Java application has a runtime class instance that enables the application to connect to the environment in which it is running. 3 * EXEC (String command)4  */5  Public classRuntimedemo {6      Public Static voidMain (string[] args) throws IOException {7Runtime r =runtime.getruntime ();8    9         //r.exec ("notepad");Ten         //r.exec ("Calc"); One         //r.exec ("shutdown-s-T 10000"); AR.exec ("shutdown-a"); -     } - } the  - /* - * Class Runtime { - * Private Runtime () {} + * private static runtime currentruntime = new Runtime (); - * public static Runtime GetRuntime () { + * return currentruntime; A  *       } at  * } -  */

Fourth type: double check lock

This can be achieved by using double-check lock, which enables both thread safety and performance to be unaffected. So what is the "double check plus lock" mechanism?

The so-called "double check plus lock" mechanism, refers to: not every time into the GetInstance method need to synchronize, but first out of sync, enter the method, first check whether the instance exists, if not exist before the following synchronization block, this is the first check,

After entering the synchronization block, check again if the instance exists, and if it does not exist, create an instance in the case of synchronization, which is the second check. In this way, you only need to synchronize once, which reduces the time wasted in the synchronization of multiple judgments.

The implementation of the double check lock mechanism uses the keyword volatile, which means that the value of a volatile variable is not cached by the local thread, and that all read and write to the variable is directly operating shared memory, ensuring that the variable is handled correctly by multiple threads.

Note: in java1.4 and in previous versions, many JVM for volatile The implementation of the keyword will cause the "double check lock" failure, so the "double check lock" mechanism can only be used in Java5 and the above version.

1  Public classTwolocksingleton {2     Private volatile StaticTwolocksingleton Singleton;3     PrivateTwolocksingleton () {4     }5      Public StaticTwolocksingleton getinstance () {6         //Check that the instance exists before entering the following synchronization block if it does not exist7         if(Singleton = =NULL) {8             //synchronization blocks, thread-safe creation instances9Synchronized (Twolocksingleton.class) {Ten                 //Check again if the instance exists, and if it does not exist, actually create the instance One                 if(Singleton = =NULL) { ASingleton =NewTwolocksingleton (); -                 } -             } the         } -         returnSingleton; -     } -}

This approach enables thread-safe creation of instances without much impact on performance. It is just the first time to create an instance of synchronization, the future does not need synchronization, thereby speeding up the speed of operation.

Singleton single-Case mode

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.