Deep understanding of the Java Memory Model (v) lock

Source: Internet
Author: User

Release of locks-acquisition of established happens before relationships

Lock is the most important synchronization mechanism in Java concurrent programming. The lock, in addition to allowing the critical area to be mutually exclusive, allows the thread that releases the lock to send a message to the thread that gets the same lock.

The following is a lock release-sample code obtained:

Class Monitorexample {
    int a = 0;
 
    Public synchronized void writer () {  //1
        a++;                             2
    }                                    //3 public
 
    synchronized void Reader () {  //4
        int i = A;                       5. ...
    }                                    6
}

Suppose thread A executes the writer () method, and then thread B executes the reader () method. According to the happens before rule, this process contains happens before relationships that can be grouped into two categories:

According to the procedure order rule, 1 happens before 2, 2 happens before 3; 4 happens before 5, 5 happens before 6.

According to the monitor lock rule, 3 happens before 4.

According to the transitivity of happens before, 2 happens before 5.

The graphical representations of the above happens before relationship are as follows:

In the figure above, each arrow links two nodes, representing a happens before relationship. Black arrows indicate program order rules, Orange arrows represent monitor lock rules, and blue arrows indicate the happens before guarantees provided after these rules are combined.

The figure above indicates that thread A has freed the lock and then threads B acquires the same lock. In the figure above, 2 happens before 5. As a result, thread A has all the visible shared variables before releasing the lock, and after thread B acquires the same lock, it immediately becomes visible to B threads.

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.