Writing thread-safe code is essentially managing access to the state , and is usually a shared, mutable state . The so-called sharing refers to a variable is accessed by multiple threads, so-called mutable refers to the value of a variable can be changed in its life cycle.
The nature of thread safety depends on how the object is used in the program, not what the object accomplishes. It is easier to design a class as thread-safe from the beginning than to modify it at a later stage.
First, the concept
Thread-Safe classes: When multiple threads access a class, the behavior of the class is still correct if you do not have to consider the scheduling and alternation of threads at runtime, and without the additional synchronization mechanism as a coordination, then we say this class is thread safe.
Example: Stateless class--it does not contain fields or domains that reference other classes. Stateless objects are always thread-safe.
Explanation: Stateless objects have only a few methods, and local variables inside the method are stored in the stack of the corresponding thread, and each thread's stack is independent.
Atomic nature:
Java Concurrency programming