Java Singleton mode, why do I need volatile

Source: Internet
Author: User

Now read the Java Concurrency Book, record it. For the Java singleton pattern, the correct code should be:

public class Testinstance {    Private volatile static testinstance instance;    public static Testinstance getinstance () {//1        if (instance = = null) {                  //2            synchronized (testinstance.class) {//3                if (instance = = null) {//4                    instance = new Testinstance ();//5                }}}        return instance;//6< c11/>}}

  

It was not previously understood why the volatile keyword was needed and later found that in the concurrency scenario, if there is no volatile keyword, there is a problem in the 5th row

For line 5th

= new Testinstance ();

Can be decomposed into 3 lines of pseudo-code

1 memory=allocate ()///Allocate memory equivalent to malloc for C

2 Ctorinstanc (memory)/Initialize Object

3 Instance=memory//Set instance point to the address you just assigned

The above code may appear reordering from 1-2-3 when the compiler is running to 1-3-2

This will cause problems in multiple threads

For example, there are 2 threads, A, b

When thread a executes the 5th line of code, the B thread comes in, and at this point a executes 1 and 3 without executing 2, and the B thread determines that instance does not return an uninitialized object directly, and there is a problem

With volatile, the above reordering will be banned in multi-threaded environments without the above problems.

Java Singleton mode, why do I need volatile

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.