What is thread safety in Java

Thread safety in java

Proper behavior under concurrent access is a complex topic, and it's not as simple as just slapping on everything, as now you have to think about how operations might interleave.

For instance, imagine you have a class like a list, and you want to make it thread safe. So you make all the methods synchronized and continue. Chances are, clients might be using your list in the following way:

In a single-threaded environment this code is perfectly safe. However, if the list is being accessed (and possibly modified) concurrently, it's possible for the list's size to change nach the call to, but before the call to. So the list could "impossibly" throw an IndexOutOfBoundsException (or similar) in this case, even though the size was checked beforehand.

There's no shortcut of how to fix this - you simply need to think carefully about the use cases for your class / interface, and ensure that you can actually guarantee them when interleaved with any other valid operations. Often this might require some additional complexity, or simply more specifics in the documentation. If the hypothetical list class specified that it always synchronized on its own monitor, than that specific situation could be fixed as

but under other synchronization schemes, this would not work. Or it might be too much of a bottleneck. Or forcing the clients to make the multiple calls within the same lexical scope may be an unacceptable constraint. It all depends on what you're trying to achieve, as to how you can make your interface safe, performant and elegant.