LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 17

tryLock while another thread holds the lock Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Thread holder = new Thread(() -> {
            lock.lock();
            try { Thread.sleep(300); } catch (InterruptedException e) { } finally { lock.unlock(); }
        });
        holder.start();
        while (!lock.isLocked()) Thread.onSpinWait();
        boolean first = lock.tryLock();
        holder.join();
        boolean second = lock.tryLock();
        lock.lock();                                   // re-entrant: same thread locks again
        System.out.println(first + " " + second + " " + lock.getHoldCount() + " " + lock.isHeldByCurrentThread());
        lock.unlock(); lock.unlock();
    }
}
  • A false true 2 true Correct
  • B true true 2 true
  • C false true 1 true
  • D false false 0 false
Correct Answer: Option A

tryLock fails while the other thread holds the lock and succeeds after it is released. The lock is re-entrant, so the hold count becomes 2 and needs two unlocks.

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