http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/ contains this code:
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);
}
The author writes:
Calling
tryConvertToWriteLock()
doesn't block but may return a zero stamp indicating that no write lock is currently available. In that case we callwriteLock()
to block the current thread until a write lock is available.
Regarding the case where tryConvertToWriteLock()
fails, did I miss something or is the author acquiring a read-lock, followed by a write-lock, and never releasing the read-lock?
Further, won't lock.writeLock()
deadlock waiting for the current thread to release its read-lock?
tryConvertToWriteLock()
fails, the user releases the read-lock before acquiring a write-lock. The article does not release the read-lock. – PendulumtryConvertToWriteLock
releases the read lock if it fails to acquire the write lock. Only if it is successful is the existing read lock upgraded. However I'm no expert on these low-level operations so I'm posting this as a comment instead of an answer. The fact that a "tutorial" contains such an error indicates how hard all this is. – Quick