Discussion
Sample21 is run - what will be the output?
public class Sample21
{
static int tally = 0;
static final Object LOCK = new Object();
public static void main(String[] args) throws InterruptedException
{
Runnable job = () ->
{
for (int i = 0; i < 2000; i++)
{
synchronized (LOCK) { tally++; }
}
};
Thread p = new Thread(job), q = new Thread(job);
p.start(); q.start();
p.join(); q.join();
System.out.println(tally);
}
}
Answer: A
Each increment happens while holding the lock on LOCK, so no two can interleave and none is lost. Releasing a monitor also publishes the writes, and the joins mean both loops have finished before the print, so 4000 is guaranteed. A private final lock object is preferred to locking the class.
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