Multi-threaded CAS

CASE

Compare And Swap (Compare And Exchange) / spins / spinlock / without lock

Exclusive locks: exclusive locks is a pessimistic locking, synchronized is a kind of exclusive lock, will cause all other threads need to lock hangs waiting thread releases the lock that holds the lock. It considered before it changes, there will be other threads to modify it, pessimistic locking efficiency is very low.

Optimistic locking (used mechanism is the CAS): Every time an unlocked assumes that there is no conflict away to complete an action, if it fails because of conflicts retry until it succeeds. It is believed that before it changes, no other threads to modify it.

Because often with cyclic operation until completion, it refers to a class of operation.

CAS (V, A, B), the value of the memory V, the expected value A, B modified value (V is equal to A, perform equal, not equal the assigned B V)

Cause ABA problem, the thread 1 is ready the value of the variable is replaced with B from A with CAS, prior to this, the value of the thread 2 the variable replaces C by A, but replace A by a C, and then found on CAS thread 1 the value of the variable still is a, so the success of CAS. But in fact this time the scene has been different and original, though CAS is successful, but the problem there may be hidden.

Solution (version AtomicStampedReference), the basis of the type of simple values ​​do not need the version number

Guess you like

Origin www.cnblogs.com/yZzcXQ/p/Thread-CAS.html