Simple interest mode (a hungry man mode, lazy mode) thread safety and problem solving

Source: Internet
Author: User
Tags volatile

Single-Case mode

1. A Hungry man mode: Create an instance when the class is loaded (thread-safe)

2. Lazy mode: Create an instance (thread unsafe) solution when the method is run: double-check

A Hungry man mode:

 Public classSingleton {//a hungry man mode//privatize a constructor    PrivateSingleton () {}//instantiating an object    Private StaticSingleton instance =NewSingleton (); //How to get an instance     Public StaticSingleton getinstance () {returninstance; }}

Lazy mode:

//Lazy Mode//privatize a constructor    PrivateSingleton () {}//instantiating an object    Private StaticSingleton instance; //How to get an instance     Public StaticSingleton getinstance () {if(Instance = =NULL) {instance=NewSingleton (); }        returninstance; }

Workaround 1 (slow)

// How to get an instance    synchronized  Public Static Singleton getinstance () {       ifnull) {           new  Singleton ();       }         return instance;    }

Workaround 2 (slow)

// How to get an instance      Public Static Singleton getinstance () {      synchronized (Singleton.  Class          ){ifnull) {              new  Singleton ();          }           return  instance;      }    }

Workaround 3 (recommended)

Cause: If the instance already exists, there is no thread-safe problem, you can get the instance directly and reduce the speed problem caused by the lock.

 Public classSingleton {//Lazy Mode//privatize a constructor    PrivateSingleton () {}//instantiating an object    Private Static volatileSingleton instance; //How to get an instance      Public StaticSingleton getinstance () {if(Instance = =NULL) {             synchronized(Singleton.class) {                 if(Instance = =NULL) {instance=NewSingleton (); }             }         }         returninstance; }}

volatile keyword

Simple interest mode (a hungry man mode, lazy mode) thread safety and problem solving

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.