Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minimum value of a counter accessed by two threads without synchronization

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?

like image 855
Tomer Avatar asked Oct 27 '25 04:10

Tomer


1 Answers

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:

  • thread A reads 0
  • thread B reads 0 and writes 1
  • thread B reads 1 and writes 2
  • ...
  • thread B reads 8 and writes 9
  • thread A writes 1
  • thread B reads 1
  • thread A reads 1 and writes 2
  • thread A reads 2 and writes 3
  • ...
  • thread A reads 9 and writes 10
  • thread A finished
  • thread B writes 2
  • thread B finished

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.

like image 69
Jack Avatar answered Oct 29 '25 18:10

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!