Java Singleton Mode Analysis

Source: Internet
Author: User

(1)/* thread security, but efficiency is relatively low. At the beginning, we need to load a class new object. This is a hunger Singleton1 mode */public class Singleton1 {private Singleton1 () {} private static final Singleton1 instance = new Singleton1 (); public static Singleton1 getInstancei () {return instance ;}} (2) // full-Chinese Singleton mode, but when multiple threads access the instance, it is not safe to return not the same object public class Singleton {private Singleton () {} private static Singleton instance; public static Singleton getInstance () {if (instance = null) instance = new Singleton (); return instance ;}} (3) // although secure, the efficiency is very low. At one time, only one thread can access and return an object public class Singleton2 {private Singleton2 () {} private static Singleton2 instance; public static synchronized Singleton2 getInstance () {if (instance = null) instance = new Singleton2 (); return instance ;}} (4) /* thread security and high efficiency multiple threads can access */public class Singleton3 {private static Singleton3 instance; private Singleton3 () {} public static Singleton3 getIstance () {if (instance = null) {synchronized (Singleton3.class) {if (instance = null) {instance = new Singleton3 () ;}} return instance ;}}

 

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.