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).