How does Lock-before protection work?

Consider the following standard Java synchronization:

public class Job {
   private Lock lock = new ReentrantLock();

   public void work() {
       lock.lock();
       try {
           doLotsOfWork();
       } finally {
           lock.unlock();
       }
   }
}

I understand, based on Javadoc, that this is equivalent to a block synchronized. I am struggling to understand how this happens on a lower level.

Lockhas a state that is volatile, when called, lock()it performs a mutable read, and then, after release, performs an unstable write. How can it be written to the state of one object, to guarantee that none of the commands from doLotsOfWorkwhich can touch many different objects will be executed out of order?

, doLotsOfWork 1000 . , , , . , - , lock/unlock, ?

+4
2

, , . : LoadLoad, LoadStore .., . , mfence lfence ( , - -).

:

i = 42;
j = 53;
[StoreStore]
[LoadStore]
x = 1; // volatile store

i j , x=1 i and j x.

volatile reads.

doLotsOfWork , lock operations.

, , , volatile read/write, . , .

, : jdk-8 Unsafe, , .

+2

Oracle :

volatile - . volatile , .

Java Concurrency :

volatile volatile. A volatile, , , volatile B volatile.

ReentrantLock , , lock.unlock() (doLotsOfWork() ), lock.lock(). doLotsOfWork() . , , , , lock.lock(), , doLotsOfWork(), lock.unlock().

+1

Source: https://habr.com/ru/post/1675403/


All Articles