Double-check idiom in Java)

Source: Internet
Author: User
The double check mode is mentioned in Article 48th in the book "Keep Itve Java", and it is pointed out that this mode is generally not applicable in Java. The structure of this mode is as follows: private resource;

Public resource getresource ()...{
If (resource = NULL )...{
Synchronized (this )...{
If (resource = NULL )...{
Resource = new resource ();
}
}
} Return resource;
}

This mode improves the following code: Public synchronized resource getresource ()...{
If (resource = NULL )...{
Resource = new resource ();
}
Return resource;
}

The purpose of this Code is to delay Resource Initialization. However, synchronization is required for each access. To reduce synchronization overhead, a dual check mode is available.

In Java, the reason why the double check mode is invalid is that the reference type is not thread-safe without synchronization. In addition to the basic types of long and double, the double check mode is applicable. For example, the following code is correct:

Private int count;

Public int getcount ()...{
If (COUNT = 0 )...{
Synchronized (this )...{
If (COUNT = 0 )...{
Count = computecount (); // time-consuming computing
}
}
} Return count;
}

The above is the general conclusion about the double-check idiom in Java. But it is not over yet, because the memory mode of Java is also being improved. Doug Lea wrote in his article: "If you declare the reference type as volatile based on the latest jsrloud Java memory model, the dual-Check Mode will work." See http://gee.cs.oswego.edu/dl/cpj/updates.html.

Therefore, to use the Double Check Mode in Java in the future, you can use the following code:

Private volatile resource;

Public resource getresource ()......{
If (resource = NULL )......{
Synchronized (this )......{
If (resource = NULL )......{
Resource = new resource ();
}
}
} Return resource;
}

Of course, it must be in Java that complies with the jsr133 specification.

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.