The difference between a a hungry man and a lazy type in a single case model

Source: Internet
Author: User

1. The A hungry man is created when the JVM is started in a singleton class, and the lazy type is created when the first instance of a singleton class is accessed, that is, the A hungry man is considered preload and the lazy load is deferred;

Sample code:

public class Eagersingleton {private static final Eagersingleton instance = new Eagersingleton (); Private Eagersingleton ( {System.out.println ("initialized..");} public static Eagersingleton getinstance () {return instance;} public void pri NT () {System.out.println ("This was an eager singleton.");}

2, a hungry man type of singleton class instances are created when the JVM is started, so do not consider multithreading problems, the lazy type needs to be synchronized (synchronized);

Sample code:

public class Lazysingleton {private static Lazysingleton instance = null; private Lazysingleton () {System.out.println ("I nitialized.. ");} public static synchronized Lazysingleton getinstance () {if (instance = = null) {instance = new Lazysingleton (); Instance public void print () {System.out.println (' This is a lazy singleton. ');}

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.