Lazy and hungry

Source: Internet
Author: User

Hunger mode: creates an object when a cut class is added.

Class Single {private single () {} Private Static Single S = new single (); pubic static single getinstance () {return s ;}}

Lazy mode: the object is created only when the getinstance () method is called.

Class Single {private single () {} Private Static Single S = NULL; public static single getinstance () {// The static lock is not used here, because if it is locked here, the lock must be determined every time an object is obtained. The efficiency is low if (S = NULL) {// The lock is determined only when the object is not empty, improving the efficiency of synchronized (single. class) {// use the bytecode object of the current class as the lock if (S = NULL) {S = new single ();}}}}}

As can be seen from the above, although the lazy mode achieves delayed loading, it will cause thread synchronization problems. To achieve synchronization, you have to apply a synchronization lock.

If you directly add the synchronized lock to the method, You must judge the lock for each call, which is less efficient. So the above code is used to achieve the same

Step. But this makes the Code a lot more complicated, so we usually use the hungry Chinese Mode to create a singleton.

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.