[英]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.