Java programming is object-oriented, and the abstraction of objects is the class, so how to make the class thread-safe can ensure the thread safety of the program.
ps: What is the thread safety issue? Multiple threads operate shared variables at the same time, and these operations are not atomic operations
How to make the class thread safe?
- Make the class stateless
There are no member variables in the class (neither static variables nor instance variables)
- Privatize variable threads
The stack is private to the thread, so the local variables defined in the method are private to the thread
ThreadLocal keeps a copy of the variable in each thread, and the copy is private to the thread
- Stack closed
- ThreadLocal
- Variables are decorated with private, and get and set methods are not provided
- The get method provides a copy
For example, there is now a get method that requires List<String> to be returned, then a new List can be created in the method, and the String object can be added to it.
- Ensure that the operation is atomic (locking)
- synchronized keyword
- CASE
- Lock
Volatile can guarantee visibility and order, and is suitable for scenarios where one write and many reads
- Valotile keywords