Search code examples
javathread-safetyatomic

Why are atomic operations considered thread-safe?


How are atomic operations made thread-safe? I've read about the subject in Wikipedia's article on thread-safety. But the article didn't really explain the process behind the scenes. In other words, why can't an "atomic" operation executed by a thread A be interrupted by a thread B?


Solution

  • An atomic operation will either be completed or not done at all. Other threads will not be able to see the operation "in progress" -- it will never be viewed in a partially complete state. This is what the word "atomic" means in this context.

    The behind-the-scenes magic for making that true will vary from implementation to implementation. For the purposes of your concurrency design, all you can rely on is that all-or-nothing guarantee on execution.