Head first design mode note (6)-single-piece Mode

Source: Internet
Author: User

 

Head first design mode note (6) --- single-piece Mode

Single-piece mode: the single-piece mode ensures that a class has only one instance and provides a global access point.

 

The single-piece mode only involves one class, so it is very simple. Note the following two points: (1) the constructor is a private member; (2) there is a static function that is responsible for instantiation.

 

 

Question 1: the dilemma of single-piece mode in multi-thread mode

Answer 1: There are three methods to process the single-piece mode in multiple threads:

(1) synchronization mechanism:

 

The synchronization method is simple and effective, but it may cause inefficiency. Synchronizing a method may reduce the execution efficiency by 100 times, so it is not suitable for frequent operations.

 

(2) Use "eager" to create an instance without delay. For details, see:

 

(3) "double check lock", reduce the use of synchronization in getinstance (), see:

 

 

 

Note: Volatile keyword reference: http://aleung.blogbus.com/logs/32090434.html

 

 

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.