Discussion
Sample29 is run - what will be the output?
public class Sample29
{
static boolean ready = false;
public static void main(String[] args) throws InterruptedException
{
Object lock = new Object();
new Thread(() ->
{
synchronized (lock) { ready = true; lock.notifyAll(); }
}).start();
synchronized (lock)
{
while (!ready) lock.wait();
}
System.out.println("ready");
}
}
Answer: A
The flag is tested inside the lock before waiting, so if the worker has already run, the while loop never waits at all and main proceeds. If it has not, wait releases the lock until the notify arrives. That is precisely why the condition-in-a-loop idiom is immune to the lost wakeup of the previous example.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development