Thread Safety for Singleton mode

Source: Internet
Author: User

Singleton mode is a relatively simple one in design mode. For cases where there is only one instance of a class, such as window manager, print buffer pool, and file system, they are all examples of prototypes. Typically, the types of objects that are accessed by different objects throughout a software system require a global access pointer, which is the application of the well-known singleton pattern.
Classic single-case mode with three types, lazy, a hungry man and lazy single-case pattern improvement
"Lazy-style" is to build this singleton object when you really use it, so it is thread insecure
Lazy type If you create an instance object without adding synchronized, the access to the object is not thread-safe.

Test the lazy type of function

Test results
A hungry man is thread-safe , creating a static object at the same time as the class is created for the system to use, and not change later.

Lazy-style improvement

Using static inner classes, the object is generated when the class is called

Thread Safety for Singleton 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: 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.