Thread-Safe single-case mode

Source: Internet
Author: User

Transferred from: http://blog.sina.com.cn/s/blog_75247c770100yxpb.html

During the interview, you will often be asked a question: Please write a singleton pattern (Singleton pattern). Well, it's not easy to write. Write one handy:

1 //Hunger Mode2  Public Final classEagersingleton3 {  4     Private StaticEagersingleton singobj =NewEagersingleton (); 5   6     PrivateEagersingleton () {7     }  8   9      Public StaticEagersingleton getsingleinstance () {Ten        returnsingobj; One     }   A}

This is the kind of notation called Hunger Mode , each object is initialized before it is used. This can lead to potential performance problems: What if the object is large? It is a huge waste to load it into memory before using this object.

In this case, we can improve the above code, using a new design concept--Lazy Loading (lazy-load Singleton)。
1 //Lazy Mode2  Public Final classLazysingleton3 {  4     Private StaticLazysingleton singobj =NULL; 5   6     PrivateLazysingleton () {7     }  8   9      Public StaticLazysingleton getsingleinstance () {Ten         if(NULL= = singobj) Singobj =NewLazysingleton (); One           returnsingobj; A     }   -}

This is the kind of notation called Lazy Mode . It uses lazy loading to ensure that objects are not initialized until they are used.

However, usually this time the interviewer will ask a new question to make a point. He would ask: Is this thread safe? The answer must be: unsafe. This is because when multiple threads may run to line Nineth at the same time, the singobj is determined to be null and initialized at the same time. So, this is the question of how to make this code thread safe? It's easy to add a synchronized in front of that method.
1 //lazy mode plus synchronized2  Public Final classThreadsafesingleton3 {  4     Private StaticThreadsafesingleton singobj =NULL; 5   6     PrivateThreadsafesingleton () {7     }  8   9      Public StaticSynchronized Threadsafesingleton getsingleinstance () {Ten         if(NULL= = singobj) Singobj =NewThreadsafesingleton (); One             returnsingobj; A     }   -}

Writing here, the interviewer may still be cunning to look at you, continue to make it difficult to: the wording of any performance problems? There must be some answer!The cost of synchronization will inevitably reduce the concurrency of the program to a certain extent。 So there is no way, on the one hand is thread-safe, there can be a very high degree of concurrency? We observed that the reason for thread insecurity is actually when initializing objects, so you can think of ways to reduce the granularity of synchronization, only to synchronize when initializing the object. It is necessary to propose a new design idea--double check Lock (double-checked lock).
1 //Double check lock2  Public Final classDoublecheckedsingleton3 {  4     Private StaticDoublecheckedsingletonsingobj =NULL; 5   6     PrivateDoublecheckedsingleton () {7     }  8   9      Public StaticDoublecheckedsingleton getsingleinstance () {Ten         if(NULL==singobj) { OneSynchronized (Doublecheckedsingleton.class){ A                      if(NULL==singobj) -Singobj =NewDoublecheckedsingleton (); -               } the          } -        returnsingobj; -     }   -}

This makes it possible for the new object to be synchronized only after it has been loaded, and other threads can determine the cost of skipping the lock directly to the 15th line of code on line Nineth. To achieve a very good degree of concurrency.

At this point, the above on the one hand to achieve the lazy-load, another aspect of the concurrency is also very good thread safety, all look perfect. This is where the interviewer may nod your answer with satisfaction. However, you said at this time, in fact, this writing is still a problem!! Where's the problem? Assuming that thread a executes to line 9th, it determines that the object is empty, then thread a executes to line 12th to initialize the object, but initialization takes time, but the address of the object already exists. At this point, thread B also executes to line nineth, it is not empty, and then jumps directly to line 15 to get the object. However, this object also not be fully initialized! What's the use of getting an object with no initialization!! There are a lot of discussions about this double-checked lock, which is currently recognized as a anti-pattern, not recommended!     So when your interviewer hears your answer, will he be holding on to it? So is there any better wording? Yes! Here again, a new paradigm is proposed--initialization on Demand Holder. This method uses an internal class to defer loading objects, and JLS (Java Language sepcification) guarantees the thread safety of this class when initializing the inner class. The greatest beauty of this notation is that the mechanism of the Java Virtual machine is fully used to ensure synchronization without a synchronized keyword.
1 //initialization on Demand Holder2  Public classSingleton3 {    4     Private Static classSingletonholder5     {    6          Public Final StaticSingleton instance =NewSingleton (); 7     }    8    9      Public StaticSingleton getinstance ()Ten     {     One         returnsingletonholder.instance;  A     }     -}

Thread-Safe 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.