You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
finalvoidlock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
elseacquire(1);
}
关键在于compareAndSetState方法:
/** * Atomically sets synchronization state to the given updated * value if the current state value equals the expected value. * This operation has memory semantics of a {@code volatile} read * and write. * * @param expect the expected value * @param update the new value * @return {@code true} if successful. False return indicates that the actual * value was not equal to the expected value. */protectedfinalbooleancompareAndSetState(intexpect, intupdate) {
returnunsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
Issue a StoreStore barrier before each volatile store
Issue a StoreLoad barrier after each volatile store.(Alternatively, if available, you can implement volatile store as an atomic instruction (for example XCHG on x86) and omit the barrier. This may be more efficient if atomic instructions are cheaper than StoreLoad barriers.)
Issue LoadLoad and LoadStore barriers after each volatile load.
On the other hand, x86 CPUs have traditionally given no ordering guarantees for loads, so the smp_mb() and smp_rmb() primitives expand to lock;addl. This atomic instruction acts as a barrier to both loads and stores.
解锁
只看一行:
protectedfinalbooleantryRelease(intreleases) {
// ...setState(c);
// ...
}
/** * Sets the value of synchronization state. * This operation has memory semantics of a {@code volatile} write. * @param newState the new state value */protectedfinalvoidsetState(intnewState) {
state = newState;
}
加锁
以NonfairSync为例:
关键在于compareAndSetState方法:
注释里写了,此方法有相当于volatile读写的内存语义。所以这个内存语义又是什么?
参考Doug lea的: The JSR-133 Cookbook for Compiler Writers
unsafe.compareAndSwapInt由Atomic::cmpxchg实现(Linux):
所以这在x86上就是加了lock前缀的cmpxhgg指令,而lock前缀在intel上便充当了读写memory barrier的作用,来自书中的摘抄L:
解锁
只看一行:
从前面Doug lea的文章中可以看出,
volatile
写会导致在后面追加一个StoreLoad屏障,而此屏障在x86上:So,也许又是一条lock前缀指令。
The text was updated successfully, but these errors were encountered: