Discussion
Sample20 is run - what will be the output?
public class Sample20
{
static volatile long total = 0;
static class Adder extends Thread
{
public void run()
{
for (int i = 0; i < 50000; i++) total++;
}
}
public static void main(String[] args) throws InterruptedException
{
Adder x = new Adder(), y = new Adder();
x.start(); y.start();
x.join(); y.join();
System.out.println(total);
}
}
Answer: D
volatile makes each read and each write atomic and visible, which is not enough: the increment is three operations and another thread can act between them, so updates are still lost. Declaring the field long does not help either; volatile only guarantees that a wide value is never seen half-written. This is the single most common misuse of the keyword.
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