0

The following code SHOULD NOT print out the right balance (100), but it is printing out 100 every time for me. Why is that? The following code does not seem to be thread safe.

public class ThreadObject implements Runnable{

    private int balance;

    public ThreadObject() {
        super();
    }

    public void add() {
        int i = balance;
        balance = i + 1;
    }

    public void run() {     
        for(int i=0;i<50;i++) {
            add(); 
            System.out.println("balance is " + balance);
        }
    }

}

public class ThreadMain {

    public static void main(String[] args) {

        ThreadObject to1 = new ThreadObject();
        Thread t1 = new Thread(to1);
        Thread t2 = new Thread(to1);
        t1.start();
        t2.start();

    }
} 

If the following code is indeed thread safe, could you explain how?

Because it looks like the code in add() is not thread safe at all. One thread could be be setting i to the current balance, but then becomes inactive while the second thread takes over and updates the balance. Then thread one wakes up which is setting balance to an obsolete i plus 1.

2 Answers 2

1

The println is probably thousands of times slower than the code that updates the balance. Each thread spends almost all of its time printing, so the likelihood of them simultaneously updating the balance is very small.

Add a small sleep between reading i and writing i + 1.

Here's a dastardly question: What is the smallest possible value of i after running the above code?

Sign up to request clarification or add additional context in comments.

2 Comments

is the smallest value 50? Because the WORST case I could think of is T1 going to sleep, T2 takes over and updates i, T1 wakes up and updates balance, T2 wakes up and update balance ... and continues in this pattern. Or is there a case worse than that?
I can't seem to figure out. Could you explain?
0

Move your println a little upper to see that this is not thread-safe. If you still can't see any change make 50 bigger (like 5000 or more).

public void add() {
    int i = balance;
    System.out.println("balance is " + balance);
    balance = i + 1;
}

public void run() {     
    for(int i=0;i<50;i++) {
        add(); 
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.