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.
Why this doesn't result in a deadlock here?
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);
Thanks in advance!