Abdul23
Abdul23

Reputation: 6025

Java 8 Stamped Lock: Why this piece of code doesnt result into a deadlock?

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!

Upvotes: 0

Views: 430

Answers (1)

WJS
WJS

Reputation: 40047

Does this help? From the API for 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.

Upvotes: 0

Related Questions