is the Java single case really written right?

Source: Internet
Author: User

The singleton mode is the simplest design pattern and the implementation is very "simple". Always thought I write no problem, until be coverity hit the face.

1. Exposure issues

Some time ago, a piece of code was coverity warning, simplify the code as follows, in order to facilitate the analysis later, I marked a number here:

Private StaticSettingsdbhelper Sinst =NULL;  Public StaticSettingsdbhelper getinstance (context context) {if(Sinst = =NULL) {//1        synchronized(Settingsdbhelper.class) {//2Settingsdbhelper Inst = sinst;//3            if(Inst = =NULL) {//4Inst =NewSettingsdbhelper (context);//5Sinst = Inst;//6            }        }    }    returnSinst;//7}

You know, this is big on the Double Checked locking mode, to ensure multithreading security, and high-performance single-case implementation, than the following singleton implementation, "forcing lattice" do not know where to go:

Private Static NULL ;    Public Static synchronized Settingsdbhelper getinstance (context context) {      ifnull) {          New  settingsdbhelper (context);    }     return Sinst;}

You a robot dare to warn me that the code is wrong, I once suspected it does not know this writing (will prove how naïve I am, PA ...) )。 Then, it seriously gives me an analysis of why this code is problematic, as shown in:

2. Cause analysis

Coverity is a static code analysis tool that simulates its actual performance. Here, for example, suppose there are two threads entering this code, where the red part is the run step resolution, and the beginning of the label indicates its run order. Detailed documentation on Coverity can be found here, here is a brief explanation of its operation as follows:

    1. Thread 1 runs to 1, and for the first time, it must be here true ;
    2. Thread 1 runs to 2, obtains the lock SettingsDbHelper.class ;
    3. Thread 1 runs to 3 and 4, assignment, at inst = sInst this time sinst or null, so continue to run down, create a new instance;
    4. Thread 1 runs to 6, modifying the value of Sinst. This step is critical, because these modifications may be reordered because they are run with other assignment operations (re-order), which can cause the Sinst value to be modified first, and new SettingsDbHelper(context) the constructor is not finished. And at this point, the program switches to thread 2;
    5. Thread 2 runs to 1, because the 4th step of the time, thread 1 has been assigned to Sinst, so sInst == null the judgment is false , thread 2 directly returned to Sinst, but this time sinst is not initialized to complete, direct use of it may cause the program to crash.

The above resolution seems to be clear, but the key is in the 4th step, why will appear re-order? Assigned, but not initialized what's going on? This is due to the memory model of Java. The problem mainly occurs in these 5 and 62 lines, where the constructor may be compiled inline (inline), and when it is run in a Java virtual machine, it is compiled to execute instructions and can be represented by the following pseudo-code:

inst = allocat(); // 分配内存  sInst = inst;  constructor(inst); // 真正执行构造函数  

When it comes to memory models, there's a bit of a touch of complexity in Java-multithreaded programming and Java memory models. Here, we can simply understand that the constructor may be divided into two blocks: allocating memory first, assigning values, and then initializing. For a detailed explanation of the Java memory Model (JMM), you can refer to this series of "in-depth understanding of the Java memory Model" in 7 articles (one, two, three, four, five, six, seven).

3. Solution

The solution to the above problem is that after Java 5, the extension keyword is introduced to volatile ensure that:

The volatile write operation of the variable does not allow the order to be scrambled with the read and write operations before it, and the volatile read operation of the variable is not allowed and the subsequent read-write disorder.

For a detailed description of the volatile keyword, refer to the in- depth understanding of the memory model (iv)above.

Therefore, the above operation, only need to add a keyword modifier to the sinst variable volatile . However, we know that the read and write operation of volatile variables is a heavy operation, so the above code can also be optimized, as follows:

Private Static volatileSettingsdbhelper Sinst =NULL;//<<< This adds the volatile Public StaticSettingsdbhelper getinstance (context context) {Settingsdbhelper Inst= Sinst;//<<< Create a temporary variable here    if(Inst = =NULL) {        synchronized(Settingsdbhelper.class) {Inst=Sinst; if(Inst = =NULL) {Inst=NewSettingsdbhelper (context); Sinst=Inst; }        }    }    returnInst//<<< Note that this returns a temporary variable}

After this modification, during the run, except for the first time, other calls would be to access the volatile variable Sinst once, which would improve the performance of 25% (Wikipedia).

Some readers have mentioned, why do we need to define a temporary variable here inst ? Through the previous interpretation of the volatile keyword function, access to volatile variables, you need to ensure some execution order, so the overhead is relatively large. This defines a temporary variable that, sInst when not empty (which is most of the case), returns a temporary variable as soon as the volatile variable is first accessed. Without this temporary variable, you need access two times, which reduces efficiency.

Finally, there is a more interesting implementation of the singleton pattern, which can delay initialization (lazy initialization), and multithreading security, but also to ensure high performance, as follows:

class Foo {      privatestaticclass  helperholder {       public  Staticfinalnew  Helper ();    }      Public Static Helper Gethelper () {        return  helperholder.helper;    }}

Lazy initialization, here is the use of Java language features, internal classes only when used, only to go back to load, thus initializing internal static variables. With regard to thread safety, this is the Java runtime automatically guaranteed to you, when loading, will automatically be invisible synchronization. It is very efficient to access the object without synchronizing the Java virtual machine and automatically canceling the synchronization.

In addition, for the principle of the final keyword, refer to the in- depth understanding of the Java memory Model (vi).

To add, some students are reminded that there is a more Hack implementation-an enumeration of individual members, supposedly the best single-instance implementation method, as follows:

 Public enum Foo {      INSTANCE;}

For details, please refer to here.

4. Summary

In Java, when it comes to multithreaded programming, the problem is much more complicated, and some bugs are even beyond your imagination. With the introduction above, you start to feel less confident about your own code running situation. In fact, do not need to worry about this, this only occurs in multithreaded programming, when encountering a critical value of access, the direct use of the SYNCHRONIZED keyword can solve most of the problems.

For Coverity, began to embrace the awe-inspiring, it was created by first-class computer scientists. Coverity as a program, itself knows much more than we do, and is more serious than me, it points out the problems must be taken seriously and analyzed.

Reference article:

    1. Https://en.wikipedia.org/wiki/Double-checked_locking
    2. Http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
    3. Http://www.oracle.com/technetwork/articles/javase/bloch-effective-08-qa-140880.html
    4. Http://www.ibm.com/developerworks/java/library/j-dcl/index.html
    5. Http://www.infoq.com/cn/articles/java-memory-model-1

is the Java single case really written right?

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.