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
In essence, many things can go wrong in a multi threaded environment (instructions reordering, partially constructed objects, same variable having different values in different threads because of caching at the CPU level etc.).
I like the definition given by Java Concurrency in Practice:
A [portion of code] is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
By correctly they mean that the program behaves in compliance with its specifications.
Contrived example
Imagine that you implement a counter. You could say that it behaves correctly if:
counter.next()
never returns a value that has already been returned before (we assume no overflow etc. for simplicity)A thread safe counter would behave according to those rules regardless of how many threads access it concurrently (which would typically not be the case of a naive implementation).
Note: cross-post on Programmers