Question 17
Back to Exercise
What is the output of the following Java program?
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!