gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:01:13 26 4
gpt4 key购买 nike

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

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 行在 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 in error”。

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

最佳答案

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

因为您可以获取一个或多个读锁,或者获取一个写锁,所以当有读锁被获取时,写锁被标记为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]

关于java - ReentrantReadWriteLock 即使其状态为 Unlocked 也无法获得锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37939572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com