What is the difference between a a hungry man and a lazy model in a single case? Where to use each fit? Why is it recommended to use a hungry man mode? _ Thread Safety

Source: Internet
Author: User
A Hungry man type:
public class singleton{
private static Singleton Singleton = new Singleton ();
Private Singleton () {}
public static Singleton getinstance () {return singletion;}
}

Lazy Type:
public class singleton{
private static Singleton Singleton = null;
public static synchronized synchronized getinstance () {
if (singleton==null) {
Singleton = new Singleton ();
}
return singleton;
}
}

Comparison:
The A Hungry man is thread-safe, creating a static object for the system to use while the class is created, not changing
Lazy If you create an instance object without adding synchronized, it can cause access to the object to be not thread-safe
Recommended to use the first one from the implementation of their biggest difference is that the lazy is delayed loading,
He created the object when it was needed, and the A hungry man was created when the virtual machine was started,
The A hungry man type does not need to pay attention to the multithreading question, the formulation is simple and clear, can use. But it is the creation of an instance when the class is loaded (a friend on the top is wrong), so if it's a factory pattern, caching a lot of instances, you have to consider the efficiency issue, because the class is loaded with all instances created with no use.
Lazy is the advantage of delay loading, the disadvantage is that the synchronization should be used (if you want to improve the words are still not possible, such as double-check), in fact, you can not sync, see your needs, create more than one or two of waste objects without reference in fact also no big deal.

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.