Thread Safety
1. What is thread safety
In the definition of thread security, the core concept is correctness. Correctness means that the behavior of a class is exactly the same as the specification. When you have a clearer definition of correctness, you can define thread safety: When multiple threads access a class, the class always shows the correct behavior, and that class is thread-safe.
For example, stateless objects must be thread-safe.
Most servlets are stateless, and thread safety becomes a problem when the servlet needs to save some information while it is processing the request.
2. atomicity
For example: statement ++i; Although the increment operation ++i is a compact syntax that makes it appear to be an operation, this operation is not atomic, and it does not act as an indivisible operation. Actually, he is three independent operations: Read I, add a value of 1, and then assign a value.
3. Race conditions
A race condition occurs when the correctness of a calculation depends on the alternating execution timing of multiple threads. The most common race condition is "check after Execution", which determines the next action through a potentially ineffective judgment result.
4. Composite operation
Assuming that there are two operations a B, if you look at the thread that executes a, when another thread executes B, either all of B is executed, or it is completely out of execution. Then A and b are atoms to each other.
5. Add Lock
For mutable state variables that may be accessed concurrently by multiple threads, the same lock is required to access it, in which case we call the state variable to be protected by this lock.
6. Activity and Performance
Performance is affected when some methods are synchronized. For example, the servlet service () method, when the synchronization method is changed, each time a thread can execute, it is against the original intention of the design, can not be a timely response to high concurrency situation.
When you use a lock, you should be aware of the functionality implemented in the code block, and whether it will take a long time to execute the block of code, or it may lead to activity or performance issues.
Java Concurrent Programming Practical reading notes (i) Thread safety