Discussion
Sample30 is run - what will be the output?
import java.util.concurrent.atomic.AtomicInteger;
public class Sample30
{
static AtomicInteger count = new AtomicInteger();
public static void main(String[] args) throws InterruptedException
{
Runnable r = () -> { for (int i = 0; i < 10000; i++) count.incrementAndGet(); };
Thread a = new Thread(r), b = new Thread(r);
a.start(); b.start();
a.join(); b.join();
System.out.println(count.get());
}
}
Answer: B
incrementAndGet performs the read, add and write as one indivisible operation, so no update can be lost however the two threads interleave. With both joins completed before the print, the total is exactly 20000. This is the fix for the plain and the volatile counter alike.
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