user2133558
user2133558

Reputation: 534

Java ReadWriteLock Reentrance

Hi i have read about the ReadWriteLock in Java but i am not sure that i have grasped the reentrance part of it. Here is two brief code examples using only one main thread to show reentrance

public class Locks {
    public static void main( String[] args ) {
        ReadWriteLock lock = new ReentrantReadWriteLock();
        lock.writeLock().lock();
        lock.readLock().lock();
        System.out.println( "Reentrance acheieved" );
        lock.readLock().unlock();
        lock.writeLock().unlock();
    }
}

and the second example

public class Locks {
    public static void main( String[] args ) {
        ReadWriteLock lock = new ReentrantReadWriteLock();
        lock.readLock().lock();
        lock.writeLock().lock();
        System.out.println( "Reentrance acheieved" );
        lock.writeLock().unlock();
        lock.readLock().unlock();
    }
}

In the first one the sysout is performed but not in the second one, why is that? Both locks are to be obtained by the same thread so we have a reentrance situation here, but the entrance is achieved only when writelock is obtained first which is strange because in non reentrant situation, the doc says that a write operation is exclusive with all the other operations (be it write or read).

Upvotes: 0

Views: 101

Answers (1)

Kevin Herron
Kevin Herron

Reputation: 6985

The answer is right there in the documentation under "Reentrancy":

This lock allows both readers and writers to reacquire read or write locks in the style of a ReentrantLock. Non-reentrant readers are not allowed until all write locks held by the writing thread have been released.

Additionally, a writer can acquire the read lock, but not vice-versa. Among other applications, reentrancy can be useful when write locks are held during calls or callbacks to methods that perform reads under read locks. If a reader tries to acquire the write lock it will never succeed.

Upvotes: 2

Related Questions