Recently I got an interview test and fumbled on this question. I will put what I explained and what I want to know what is the correct behavior. I want to ensure that my understanding is correct , not for the sake of interview but to get better.
**Que:**We have a counter below( java code) and if say 20 threads run this code in parallel then will the value of a and b will be same? What if b Is not valiatile
My Answer: may or may not be. Why - when there is a race condition then no guarantee that different threads will see updated values of b or a and in that case values would be different. Here, I don't think volatile makes any difference.
I wrote a simple client and ran this code with number of threads upto 50 on 16 core laptop and I could see same values for a and b when tried run for 500 times. However, when I increased number of threads to 200 then sometimes I saw different values.
Question - what is the right answer to this and is my understanding correct? And why did I see different results on my laptop?
public class VolatileCounter implements Runnable {
private static int a;
private volatile static int b;
public VolatileCounter() {
}
@Override
public void run() {
try{
b++;
a++;
}finally {
//some system println....
}
}
public void printNumbers() {
System.out.println(b);
System.out.println(a);
}
}