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.