Security issues

In-process threads share memory — the heap, where class member variables reside in heap memory. Data in heap memory can be accessed by any thread, so there is a risk that data can be accidentally modified.

plan

Position the isolation

A single thread shares memory — the stack — where local variables are stored

Data isolation

ThreadLocal: Copies N copies of the data in the heap, one for each thread. Each thread can only manipulate its own copy of the data. Thread-local data is still stored in heap memory, similar to a shared bike, in a common area, but with each person using it

read-only

The final modification

Pessimistic locking

When adding a lock to the heap memory data, the lock must be acquired before the operation. Releasing the lock after the operation is completed is suitable for the scenario with a large number of threads. Because acquiring the lock and releasing the lock also requires a certain cost, when the number of threads is small, it is also a waste to acquire the lock frequently

Optimistic locking

In the case of small concurrency, the probability of data modification is low. In this case, optimistic locking CAS is applied: assuming that the data will not be modified, ABA will be restarted if the data is modified: add version number to the data, as long as the data is modified, version number +1 — used to determine whether the data has been modified