A single case pattern in Java thread safety _java

Source: Internet
Author: User
Tags static class

Copy Code code as follows:

Package net.kitbox.util;
/**
*
* @author Lldy
*
*/
public class Singleton {
Private Singleton () {
}
private Static Class singletonholder{
private static Singleton instance = new Singleton ();
}
public static void Method () {
Singletonholder.instance._method ();
}
private void _method () {
System.out.println ("Singleton method!");
}
public static void Main (string[] args) {
Singleton.method ();
}
}

This notation utilizes the loading principle of the ClassLoader, where each class is only loaded once, so that a single instance object is generated when its internal static class is loaded, and the process is thread safe.

where method () encapsulates the private method of an internal single Instance object and is used as an external interface, so that it can be invoked as follows

Copy Code code as follows:

Singleton.method ();
Frequent use is more convenient than common singleton.getinstance (). Method ()

Another way to do this is by using enumerations.

The above is the entire content of this article, I hope you can enjoy.

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.