Search code examples
javamultithreadingdata-consistency

How does thread interference actually happens in the `Counter` example class?


I'm trying to learn the concept of thread interference and have encountered the following example in Java Tutorial Oracle:

class Counter {
    private int c = 0;

    public void increment() {
        c++;
    }

    public void decrement() {
        c--;
    }

    public int value() {
        return c;
    }

}

The Oracle tutorial mentioned that if there are two threads trying access variable c, it can result in thread interference where the change made by one thread is not seen by the other.

However, it did not provide any code to actually explain the concept. Could someone please provide a code example based the Counter class to demonstrate how thread interference actually happens?


Solution

  • Rather than the code, I prefer explaining what will happen. Suppose 2 threads, A and B are accessing the same counter object, A calls increment and B calls decrement. Either of these operations consist of at least 3 steps.

    1. Read C from memory
    2. Increment or decrement C
    3. Write back C to the memory.

    When A and B try to increment and decrement at the same time, One thread may read C from memory(step 1), while the other thread is at step 2. in such cases if the initial value of c was 5, first Thread A read and increment it to 6. Then Thread B read and decrement it to 4. Remember, B is doing these changes before A finish writing c back to the memory. Since the steps are overlapped, the changes made by one thread will not be visible to the other resulting in the final value of c being either 6 or 4. But actually what we expected was 5.

    This is an example of two threads interfering each other. To avoid this we use thread synchronization.