Memory barriers, volatile, locks, final

1. Memory barriers at the hardware layer: Load Barrier and Store Barrier

Role: Prevent reordering of instructions on both sides of the barrier;

      Forcing the dirty data in the write buffer/cache, etc. to be written back to main memory, invalidating the corresponding data in the cache.

For the Load Barrier, inserting the Load Barrier before the instruction can invalidate the data in the cache and force the data to be reloaded from the main memory;

For the Store Barrier, inserting the Store Barrier after the instruction allows the latest data update in the write cache to be written to main memory, making it visible to other threads.

 

2. volatile memory semantics

When a volatile variable is written, the JMM will refresh the value of the shared variable in the local memory corresponding to the thread to the main memory.

When reading a volatile variable, the JMM will invalidate the local memory corresponding to the thread, requiring the thread to read the data from the main memory.

 

3. The implementation of volatile

According to the volatile reordering rules, insert Store Store barriers before write operations; insert storeload barriers after write operations; insert loadload and loadstore barriers after read operations

(based on conservative strategy)

 

4. Memory semantics of locks

Lock release has the same semantics as volatile write. Lock acquisition has the same semantics as volatile read.

 

5. The underlying implementation of the lock

Relying on volatile variables and cas operations to achieve.

 

6. Final field memory semantics

The final fields of an object are properly initialized before the object reference is visible to any thread, whereas normal fields do not have this guarantee.

 

7. Final field reordering rules

final fields are primitive data types:

There is no reordering between the writing of a final field within the constructor and the subsequent assignment of a reference to the constructed object to a reference variable.

There is no reordering between an initial read of a reference to an object containing a final field and a subsequent initial read of the final field.

The Final field is a reference data type:

There is no reordering between writing to a field of a final referenced object within the constructor and subsequent assignment of a reference to the constructed object to a reference variable outside the constructor.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325219600&siteId=291194637