我在"实践中的Java并发"第14.6.1节中阅读了有关ReentrantLock实现的一些细节,注释中的某些内容让我感到困惑:
因为受保护的状态操作方法具有易失性读取或写入的内存语义,并且ReentrantLock 只有在调用getState之后才会读取所有者字段并且仅在调用setState之前写入它,ReentrantLock可以依赖于同步状态的内存语义,因此避免进一步同步见第16.1.4节.
它引用的代码:
protected boolean tryAcquire(int ignored) {
final Thread current = Thread.currentThread();
int c = getState();
if (c ==0) {
if (compareAndSetState(0, 1)) {
owner = current;
return true;
}
} else if (current == owner) {
setState(c+1);
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我相信这是对简化代码nonfairTryAcquire的ReentrantLock.Sync.
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true; …Run Code Online (Sandbox Code Playgroud) java concurrency multithreading synchronization memory-barriers