Reputation: 21245
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.
Upvotes: 0
Views: 77
Reputation: 21257
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();
}
}
Upvotes: 0
Reputation: 185852
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?
Upvotes: 1