Synchronized
Java’s primary tool for rendering interactions between threads predictably is the synchronized keyword.
Many programmers think of synchronized strictly in terms of enforcing a mutual exclusion semaphore (mutex) to prevent execution of critical sections by more than one thread at a time. Unfortunately, that intuition does not fully describe what synchronized means.
Synchronize is more than mutual exclusion : The semantics of synchronized do indeed include mutual exclusion of execution based on the status of a semaphore, but they also include rules about the synchronizing thread’s interaction with main memory. In particular, the acquisition or release of a lock triggers a memory barrier – a forced synchronization between the thread’s local memory and main memory. (Some processors – like the Alpha – have explicit machine instructions for performing memory barriers.) When a thread exits a synchronized block, it performs a write barrier – it must flush out any variables modified in that block to main memory before releasing the lock. Similarly, when entering a synchronized block, it performs a read barrier – it is as if the local memory has been invalidated, and it must fetch any variables that will be referenced in the block from main memory.
The proper use of synchronization guarantees that one thread will see the effects of another in a predictable manner. Only when threads A and B synchronize on the same object will the JMM guarantee that thread B sees the changes made by thread A, and that changes made by thread A inside the synchronized block appear atomically to thread B (either the whole block executes or none of it does.)
Furthermore, the JMM ensures thatsynchronizeblocks that synchronize on the same object will appear to execute in the same order as they do in the program.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/258476.html
標籤:區塊鏈
