gpt4 book ai didi

java - StampedLock.writeLock() 是否释放当前线程持有的读锁?

转载 作者:行者123 更新时间:2023-11-30 07:48:31 24 4
gpt4 key购买 nike

http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/包含此代码:

StampedLock lock = new StampedLock();
long stamp = lock.readLock();
try {
if (count == 0) {
stamp = lock.tryConvertToWriteLock(stamp);
if (stamp == 0L) {
System.out.println("Could not convert to write lock");
stamp = lock.writeLock();
}
count = 23;
}
System.out.println(count);
} finally {
lock.unlock(stamp);
}

作者写道:

Calling tryConvertToWriteLock() doesn't block but may return a zero stamp indicating that no write lock is currently available. In that case we call writeLock() to block the current thread until a write lock is available.

关于 tryConvertToWriteLock() 失败的情况,我是否遗漏了什么,或者作者获取了一个读锁,然后是一个写锁,并且从未释放读锁?

此外,lock.writeLock() 不会死锁等待当前线程释放其读锁吗?

最佳答案

我认为本文提供的代码示例存在错误。根据https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/locks/StampedLock.html

Like Semaphore, but unlike most Lock implementations, StampedLocks have no notion of ownership. Locks acquired in one thread can be released or converted in another.

此外,他们还提供了以下示例代码:

void moveIfAtOrigin(double newX, double newY) { // upgrade
// Could instead start with optimistic, not read mode
long stamp = sl.readLock();
try {
while (x == 0.0 && y == 0.0) {
long ws = sl.tryConvertToWriteLock(stamp);
if (ws != 0L) {
stamp = ws;
x = newX;
y = newY;
break;
}
else {
sl.unlockRead(stamp);
stamp = sl.writeLock();
}
}
} finally {
sl.unlock(stamp);
}
}

注意他们如何在获取写锁之前释放读锁。

关于java - StampedLock.writeLock() 是否释放当前线程持有的读锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216525/

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