[英]Why is there no synchronized keyword used in Java lock implementations?
synchronized
在Java中用於處理互斥體的各種事情。 但是,像Java中的ReentrantLock
這樣的Lock
接口的實現不使用此關鍵字。 所有代碼看起來都只是普通代碼。 那它如何處理地球上的多個線程?
我相信以下代碼片段是相關的:
Sync
ReentrantLock
的tryAcquire
方法
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
Sync
擴展了AbstractQueuedSynchronizer
和相關的代碼:
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
所以似乎沒有使用synchronized
關鍵字,那么它如何保證互斥?
從Java 1.5(?)開始,JVM支持使用所謂的Compare-And-Swap方法進行硬件鎖定。 只需按照這些來源,直到調用它為止。
另請參閱Doug Lea的文章以獲得更好的理解: http : //gee.cs.oswego.edu/dl/papers/aqs.pdf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.