I recently received an interview test and fumbled on this issue. I will tell you what I explained and what I want to know what is the right behavior. I want my understanding to be right, not for the sake of an interview, but to get better.
** Que: ** We have a counter below (java code), and if it is said that 20 threads run this code in parallel, will the value of a and b be the same? What if b is not valiatile
My answer: may or may not be. Why - when there is a race condition, there is no guarantee that different threads will see the updated values ββof b or a, in which case the values ββwill be different. Here, I do not think that variability matters.
I wrote a simple client and ran this code with up to 50 threads on a 16-core laptop, and I could see the same values ββfor a and b when I tried to work 500 times. However, when I increased the number of threads to 200, sometimes I saw different values.
The question is what is the correct answer to this and do I understand correctly? 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 {
}
}
public void printNumbers() {
System.out.println(b);
System.out.println(a);
}
}
source
share