I've been told in an interview that the minimum value for counter after running the following code is 2. How is that possible?
class ThreadsConflict {
private static int counter = 0;
public static void main(String[] args) throws InterruptedException{
Thread t1 = new A();
Thread t2 = new A();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter);
}
static class A extends Thread {
public void run() {
for(int i = 0; i < 10; i++) {
counter++;
}
}
}
}
I can understand why it will be 10 if they are interleaved and the ++ operator is conflicting but how is it possible that it will be under 10?
That's because interleaving occurs between non atomic operations so counter++ can be interrupted in the middle, sort of:
int tmp = counter;
/* threads gets interrupted here */
counter = tmp + 1;
This may lead to corner case situations as:
Mind that this is because i is used as a condition so exactly 10 iterations are done, if you were using directly counter then you'll be guaranteed to have at least 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With