ReentrantReadWriteLock 即使其状态为 Unlocked 也无法获得锁定

ReentrantReadWriteLock fails to get lock even when its state is Unlocked

我正在尝试使用以下代码锁定线程:

Lock lock = readLock ? getLock(key).readLock() : getLock(key).writeLock();
try {
    boolean locked = lock.tryLock(DEFAULT_TRY_TIME, DEFAULT_TRY_TIME_UNIT); //line 3
    // If false, lock is not acquired
    if (!locked) {
        throw new TryLockTimeoutException(
                key + ": Failed to acquire " + lock + " within " + DEFAULT_TRY_TIME_STRING);
    }
}

第 3 行 returns 在 30 分钟后为 false 因此 TryLockTimeoutException 抛出错误为:

com.concurrent.TryLockTimeoutException: keyIp : Failed to acquire java.util.concurrent.locks.ReentrantReadWriteLock$WriteLock@74be2cee[Unlocked] within 30MINUTES
    at com.concurrent.NeAccessLockMap.acquireReadOrWriteLock(NeAccessLockMap.java:72)

请注意锁定状态显示为错误解锁。

我无法理解为什么会这样?为什么即使锁是空闲的,线程也无法获得锁。

在您的示例中,您尝试获取写锁,但读锁已被锁定,这会阻止您获取写锁。

因为您可以获取一个或多个读锁,或者获取一个写锁,所以当有读锁被获取时,写锁被标记为Unlocked

试试下面的代码:

ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
new Thread() {
    @Override
    public void run() {
        readWriteLock.readLock().lock();
        try {
            // block the read lock
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}.start();
if (!readWriteLock.writeLock().tryLock(1, TimeUnit.SECONDS)) {
    System.out.println(readWriteLock);
    System.out.println(readWriteLock.readLock());
    System.out.println(readWriteLock.writeLock());
}

输出如下:

java.util.concurrent.locks.ReentrantReadWriteLock@31221be2[Write locks = 0, Read locks = 1]
java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock@377dca04[Read locks = 1]
java.util.concurrent.locks.ReentrantReadWriteLock$WriteLock@728938a9[Unlocked]