A thread-safe lazy single-case design pattern

Source: Internet
Author: User

First review the simple interest design pattern: The simple interest design pattern is a way for a class to create only one instance of an object for outside use. Simple interest design patterns are divided into lazy and a hungry man: A Hungry man is thread-safe:
1 //a hungry man type simple interest design mode:2  classsingle{3      Private Static FinalSingle =NewSingle ();4      PrivateSingle () {}5       Public StaticSingle getinstance () {6           returns;7      }8}
A hungry man thread-safe, can be used to get the instance of the method to add synchronization or add synchronization code block, but this will lose time efficiency, so that every call will determine whether to have a lock, then you can double the null and synchronous code block method to achieve thread safety, and thus improve the efficiency
1 //a thread-safe lazy single-case design pattern2  Public classSingledemo {3 //lazy, thread-safe, double-judge plus sync thread4      Private StaticSingledemo singledemo=NULL;5      PrivateSingledemo () {}6       Public StaticSingledemo getinstance () {7           if(singledemo==NULL) {8               synchronized(Singledemo.class) {9                    if(singledemo==NULL) {TenSingledemo =NewSingledemo (); One                    } A               } -           } -           returnSingledemo; the      } -}

A thread-safe lazy single-case design pattern

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.