java--single case mode (Singleton)--design mode three

Source: Internet
Author: User


1, overview of the singleton mode:
(1) The Singleton object is a common design pattern, in Java application, the Singleton object can be guaranteed in a
in the JVM, only one instance of the object exists, and there are several benefits to this pattern:① Some classes are created more frequently, and for some large objects, this is a significant overhead② eliminates the new operator, reduces the frequency of system memory usage, and reduces GC pressure③ Some classes, such as the exchange's core trading system, control the trading process, if the class can createmultiple words, the system is completely chaotic, (such as a military presence of multiple commanders at the same time command, will certainly be disorderly), so only the single-instance mode can be used to ensure that the core trading server independently controls the entire process.          (2) Specific steps:① a hungry man in single-case mode:


② The following code is a lazy type in a singleton pattern:




This class can meet the basic requirements, however, like this without the thread security class, if we put himput in the multi-threaded environment, it must be a problem, how to solve? The first thing we'll think about is getinstancemethod Add synchronized keyword, as follows:



However, thesynchronized keyword is locked by this object, and this usage will have a performancedrop, because every time you call getinstance (), you have to lock the object, in fact, only the first time you createobjects need to be locked and then not needed, so this place needs to be improved and we modify it toHere's a little bit:



seems to solve the problem mentioned earlier, add the synchronized keyword to the inside, that is, when the call when there is no need to lock, performance has a certain increase, but, such a situation, there may beproblem, look at the following situation:creating objects and assigning operations in Java directives is done separately, which means that instance =new Singleton (); The statement is executed in two parts, but the JVM does not guarantee the sequencing of the two operations,that is, it is possible that the JVM allocates space for the new singleton instance and assigns it directly to the instancemember, and then initialize the singleton instance so that it can go wrong, we have A, B twothread as an example:a > A, B threads enter the first if judgment at the same timeB > A first enters the synchronized block, because instance is null, so it executes instance= new Singleton ();C > because of the optimization mechanism inside the JVM, the JVM first draws some of the singleton instances assigned to theblank memory and assign a value to the instance member (note that at this point the JVM does not start initializing this instance),and a left the synchronized block.d > B entered the synchronized block because instance was not null at this time, so it left immediately.synchronized The block and returns the result to the program that called the method   e > When the B thread intends to use the singleton instance, it finds that it was not initialized, and the error occurred, so the program is still possible error, in fact, the program is very complex in the running process, from this point we cansee, especially in the writing multi-threaded environment of the program is more difficult, challenging, we have done the program intoOne-Step optimization:



The reality is that the singleton pattern uses internal classes to maintain the implementation of the Singleton, and the mechanism inside the JVM can guaranteeWhen a class is loaded, the loading process of this class is thread-mutually exclusive, so that when we first callgetinstance, the JVM can help us ensure that instance is created only once and will guaranteeThe memory assigned to instance is initialized so that we don't have to worry about the problem above, and the methodwill only use the mutex at the first call, which solves the performance problem, so we can temporarilysummarize a perfect singleton pattern:



in fact, it's perfect, not necessarily, if an exception is thrown in the constructor, the instance will never be created, there will be errors, so that the very perfect thing is not, we can only according to the actual situation, choose the mostthe implementation of their own application scenarios, but also some people do so, because we only need to create the class when theTo synchronize, so as long as the creation and getinstance separate, separately for the creation plus synchronized keywords, is also possible:



considering performance, the entire program only needs to create one instance, so performance has no impact
Supplement: Use Shadow instance to synchronize updates for properties of Singleton objects



2, Summary:
(1) The singleton mode is simple to understand, but it is difficult to realize it concretely .
(2)synchronized keyword lock is the object, in use, must be early appropriate place with (Note that you need to use locks for objects and procedures, which may sometimes not be the whole object and the entire process. )lock), here, the singleton mode is basically complete, but there is a problem, that is, the use of class static method,It is also possible to achieve the effect of a singleton mode, what is the difference here? ① First, a static class cannot implement an interface (from the point of view of a class), but it destroys the static because the method of static modification is not allowed in the interface, so even if it is implemented it is non-static .② Second, Singleton can be delayed initialization, static class is usually initialized in the first time , the reasonlazy loading because some classes are quite large, so lazy loading can help improve performance③ again, a singleton class can be inherited, its methods can be replicated, but static class internal methods are static, cannot be replicated④ Finally, the Singleton class is more flexible, after all, from the implementation is only a different Java class, as long as the single case to meet theBasic requirements, you can implement some of the other functions as you like, but static classes do not, from the abovein these generalizations, we can see the difference between the two, but, on the other hand, the last one we realized aboveSingleton mode, the internal is a static class to achieve, so, there is a great correlation, but weconsidering the different aspects of the problem, the combination of the two ideas can create the perfect solution, just likeHashMap is implemented using array + linked list

3, static code block write single example:
(1) Static code blocks are loaded, and static blocks are executed only once, so that only one object in memory is guaranteed






java--single case mode (Singleton)--design mode three

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.