The following list of "Concurrency Tips" lists the main concepts and rules introduced in the first part (chapters two to five).
- The mutable state is critical (It's The mutable state,stupid).
All concurrency problems can be attributed to the coordination of access to the concurrency state. The fewer mutable states, the easier it is to ensure thread safety.
- Try to declare the domain as the final type, unless you want them to be mutable.
- Immutable objects must be thread-safe.
Immutable objects can greatly reduce the complexity of concurrent programming. They are simpler and more secure and can be freely shared without the use of locks or protected replication mechanisms.
- Encapsulation helps manage complexity.
While writing a thread-safe program, you can save all the data in a global variable, but why do you do this? Encapsulating data in objects is easier to maintain: it is easier to follow synchronization policies by encapsulating the synchronization mechanism in objects.
- Use locks to protect each variable variable.
- The same lock is used when all variables in the same invariant condition are protected.
- Locks are held during a composite operation.
- If there is no synchronization mechanism when accessing the same mutable variable from multiple threads, there is a problem with the program.
- Don't pretend to be smart enough to infer that you don't need to use synchronization.
- Consider thread safety during the design process, or explicitly indicate in the documentation that it is not thread-safe.
- Document the synchronization policy.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Java Concurrency in practice] Chapter two to five summary