Java Thread Safety Single-instance mode implementation (i) and explanation

Source: Internet
Author: User

Singleton mode ensures that a class has only one instance and provides a global access point.

Java source code:

public class Singleton {private static Singleton uniqueinstance = new Singleton (), private Singleton () {} public static Si Ngleton getinstance () {return uniqueinstance;}}

because Uniqueinstance is a class variable, there is only one; it refers to an instance of the Singleton class, which is created when the singleton is initialized. The next step is to explain the specific process that the Singleton class unique instance was created.


When an active reference is made to a class, the class is initialized if the class has not been initialized. There are only six cases where the active reference to a class is:

By the six cases listed, when we first get an instance of the class through Singleton.getinstance (), the initialization of the Singleton class is triggered.

From loading to initializing a class, you need to go through the following process:

In the prepare phase, the uniqueinstance is assigned null, and in the initialization phase, the uniqueinstance is assigned new Singleton (), and an instance of the Singleton class is created, because only the first The Singletonis initialized when the singleton.getinstance () is called, so this is also the only time to create the Singleton instance, which is called Singleton.getinstance () the only instance that was obtained--Singleton.

Reference

1. "In the design mode"

2. BEIJING Santhiya Garden deep Java Virtual Machine video tutorial)

Java Thread Safety Single-instance mode implementation (i) and explanation

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.