Does it mean that two threads can\'t change the underlying data simultaneously? Or does it mean that the given code segment will run with predictable results when multiple t
Let's answer this by example:
class NonThreadSafe {
private int counter = 0;
public boolean countTo10() {
count = count + 1;
return (count == 10);
}
The countTo10 method adds one to the counter and then returns true if the count has reached 10. It should only return true once.
This will work as long as only one thread is running the code. If two threads run the code at the same time various problems can occur.
For example, if count starts as 9, one thread could add 1 to count (making 10) but then a second thread could enter the method and add 1 again (making 11) before the first thread has a chance to execute the comparison with 10. Then both threads do the comparison and find that count is 11 and neither returns true.
So this code is not thread safe.
In essence, all multi-threading problems are caused by some variation of this kind of problem.
The solution is to ensure that the addition and the comparison cannot be separated (for example by surrounding the two statements by some kind of synchronization code) or by devising a solution that does not require two operations. Such code would be thread-safe.