Java 8 Stamped Lock:为什么这段代码不会导致死锁? [英] Java 8 Stamped Lock: Why this piece of code doesnt result into a deadlock?
问题描述
在尝试理解Java 8中的乐观锁时,我遇到了以下代码. 此处的原始博客
In my attempt to understand Optimistic locking in Java 8,I came across the below piece of code. Original Blog Here.
如博客中所述,这段代码试图将读取锁转换为写入锁.如果将读取锁转换为写入锁失败,则代码会请求显式写入锁.
As explained in the blog, this piece of code is attempting to convert a read lock into a write lock.The code requests an explicit write lock if conversion of read lock to write lock failed.
这使我感到困惑当父线程已经持有读取锁时,如何期望授予显式写入锁?看起来读取锁似乎并没有被释放强制请求写锁定之前的时间点.以我的错误理解,线程将无限期地等待写锁,因为从不释放读锁而导致死锁.
It puzzles me How can it be expected that the explicit write lock get granted when the parent thread is already holding a read lock? It doesn't look like the read lock is getting released at any point before a write lock is forcefully requested. To my flawed understanding, the thread would wait infinitely for write lock as the read lock is never released creating a deadlock.
为什么这不会导致僵局?
ExecutorService executor = Executors.newFixedThreadPool(2);
StampedLock lock = new StampedLock();
executor.submit(() -> {
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);
}
});
stop(executor);
提前谢谢!
推荐答案
有帮助吗?从tryConvertToWriteLock
如果锁定状态与给定的标记相匹配,则自动执行以下操作之一.如果该图章表示持有写锁,则将其返回. 或者,如果有读锁(如果有写锁),则释放读锁并返回写标记.或者,如果是乐观读,则仅在立即可用时才返回写标记.在所有其他情况下,此方法均返回零.
If the lock state matches the given stamp, atomically performs one of the following actions. If the stamp represents holding a write lock, returns it. Or, if a read lock, if the write lock is available, releases the read lock and returns a write stamp. Or, if an optimistic read, returns a write stamp only if immediately available. This method returns zero in all other cases.
这篇关于Java 8 Stamped Lock:为什么这段代码不会导致死锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!