Java design Pattern-Singleton mode-Lazy loading

Source: Internet
Author: User

First of all, recommend the best way to implement the Singleton mode (no one)

public class Manager {

Private Manager () {

}

public static Manager getinstance () {
return managerholder.instance;
}

private Static Class Managerholder {
Private static final Manager instance = new manager ();
}
}

Then explain why this is the way:

* The inner class is loaded by the ClassLoader only when needed, enabling lazy loading, which is to instantiate a manager when needed, and is the only one

* Also because instance is a static final type, ensuring that only one instance exists in memory and can only be assigned once, ensuring thread safety

(Even if multiple threads concurrently access the getinstance () method in high concurrency, the instance's uniqueness can be guaranteed)

Other implementations that do not adopt an inner class are the best they have seen at this time:

public static class Singletonoptimizelazy {
static Singletonoptimizelazy instance = NULL;
public static Singletonoptimizelazy getinstance () {
if (instance = = null) {
CreateInstance ();
}
return instance;
}
Private synchronized static Singletonoptimizelazy CreateInstance () {
if (instance = = null) {
Instance = new Singletonoptimizelazy ();
}
return instance;
}
}

The main idea of this solution is to abstract the process of instantiation into a sychronized method so that lazy loading and concurrency security can also be implemented.

However, it is still recommended to use the internal class solution

Java design Pattern-Singleton mode-Lazy loading

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.