LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 18

Readers sharing a ReadWriteLock Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
        CountDownLatch bothReading = new CountDownLatch(2), release = new CountDownLatch(1);
        Runnable reader = () -> {
            rw.readLock().lock();
            try { bothReading.countDown(); release.await(); } catch (InterruptedException e) { }
            finally { rw.readLock().unlock(); }
        };
        Thread r1 = new Thread(reader), r2 = new Thread(reader);
        r1.start(); r2.start();
        bothReading.await();                                   // two readers hold the lock at the SAME time
        int readers = rw.getReadLockCount();
        boolean writerCouldEnter = rw.writeLock().tryLock();    // a writer must wait for all readers
        release.countDown();
        r1.join(); r2.join();
        boolean writerNow = rw.writeLock().tryLock();
        System.out.println(readers + " " + writerCouldEnter + " " + writerNow + " " + rw.isWriteLocked());
    }
}
  • A 2 false true true Correct
  • B 1 false true true
  • C 2 true true true
  • D 2 false false false
Correct Answer: Option A

Many readers can hold the read lock together, but the write lock is exclusive: it is available only when no reader holds the lock.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links