Sobes.tech
Junior — Senior

Determining the result of an uncontrolled counter in a multithreaded environment

livecode

Task condition

In the main method, two threads are created that work with the same Test2 object:

  • the first thread (started with new Thread(test2).start()) calls the inc() method four times;
  • the second thread (the main thread) decreases the counter value four times by calling dec() directly. Both threads use the same instance of the class, so the increment and decrement operations can occur simultaneously without synchronization. It is necessary to determine what value the get() method might return after both sequences of operations are completed, and under what circumstances a zero might be obtained.
public class Test2 implements Runnable {

    private int counter;

    public void inc() {
        counter++;
    }

    public void dec() {
        counter--;
    }

    public int get() {
        return counter;
    }

    @Override
    public void run() {
        for (int i = 0; i < 4; i++) {
            inc();
        }
    }

    public static void main(String[] args) {
        Test2 test2 = new Test2();
        new Thread(test2).start();
        for (int i = 0; i < 4; i++) {
            test2.dec();
        }
        System.out.println(test2.get());
    }
}