Android classic Singleton mode and Android Classic Mode

Source: Internet
Author: User

Android classic Singleton mode and Android Classic Mode

SInstance is not initialized when the Singleton class is loaded for the first time. sInstance is initialized only when the Singleton getInstance method is called for the first time. Therefore, the first call to the getInstance method will result in

The SingletonHolder class is loaded on virtual machines. This method not only ensures thread security, but also ensures the uniqueness of the SingletonHolder object and also delays Singleton instantiation. Therefore, this is the recommended Singleton mode.

Public class Singleton {private Singleton () {}; public static Singleton getInstance () {return SingletonHolder. sInstance;}/*** static internal class */private static class SingletonHolder {private static final Singleton sInstance = new Singleton ();}}

 

 

 

 

Although this method seems to be quite good, it seems that the dual check lock (DCL) will fail.

public class MyImageLoader extends ImageLoader {    private static MyImageLoader instance;        public static MyImageLoader getInstance() {        if (instance == null) {            synchronized (MyImageLoader.class) {                if (instance == null) {                    instance = new MyImageLoader();                }            }        }        return instance;    }        protected MyImageLoader() {            }}

 

 

 

 

 

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.