In many cases we just need a simple, efficient, thread-safe increment-decrement scheme. Note that there are three conditions: simple, which means that it is easier for programmers to operate the underlying or implement as little as possible, and that efficiency means less resource consumption, faster process processing, and thread safety, which guarantees the correctness of the data in multiple threads. These three conditions look relatively simple, but they are difficult to achieve satisfactorily.
Typically, in Java, ++i or-I are not thread-safe, there are three separate operations: get the current value of the variable, +1/-1 the value, and write back the new value. In the case where no additional resources are available, only the lock can be used to ensure that the three operations of read-write are "atomic".
Java 5 Adds the Atomicinteger class, which contains methods Getandincrement () and Getanddecrement (), which implement atomic and atomic subtraction, but the difference is that the two operations do not use any locking mechanism. belongs to a lock-free operation.
Prior to JDK 5, the Java language was guaranteed to be synchronized by the Synchronized keyword, which would result in a lock (later chapters will also talk about locks).
The lock mechanism has the following issues:
(1) Under the multi-thread competition, the locking and release lock will lead to more context switching and scheduling delay, causing performance problems.
(2) A thread holding a lock causes all other threads that require this lock to hang.
(3) If a high-priority thread waits for a thread with a lower priority to release the lock, it causes the priority to be inverted, causing a performance risk.
Volatile is a good mechanism, but volatile does not guarantee atomicity. Therefore, for synchronization to eventually return to the lock mechanism.
An exclusive lock is a pessimistic lock, and synchronized is an exclusive lock that causes all other threads that need to be locked to hang, waiting for the thread that holds the lock to release the lock. Another more effective lock is the optimistic lock. The so-called optimistic lock is that each time without locking but assuming that there is no conflict to complete an operation, if the conflict failed to retry until successful.
CAS operations
The mechanism used for optimistic locking above is cas,compare and Swap.
CAS has 3 operands, a memory value of V, an old expected value of a, and a new value to be modified B. If and only if the expected value A and the memory value of the V phase, the memory value of V is modified to B, otherwise do nothing.
Non-blocking algorithm (nonblocking algorithms)
Failure or suspend of one thread should not affect other threads ' failed or suspended algorithms.
Modern CPUs provide special instructions to automatically update shared data and detect interference from other threads, and Compareandset () replaces the lock with these.
Take out Atomicinteger to study how the data is correct without a lock.
private volatile int value;
In the first place, there is no doubt that a volatile primitive is required to ensure that the data between threads is visible (shared) without a lock, so that the value of the variable can be read directly when it is obtained.
Public final int get () {
return value;
}
Then let's see how ++i did it.
Public final int Incrementandget () {
for (;;) {
int current = get ();
int next = current + 1;
if (Compareandset (current, next))
return next;
}
}
The CAS operation is used here, each time the data is read from memory and then the CAS operation is performed with the result of +1, if successful, the result is returned, otherwise it is retried until it succeeds.
Instead, Compareandset uses JNI to perform the operation of the CPU instructions.
Public final Boolean compareandset (int expect, int update) {
Return Unsafe.compareandswapint (this, valueoffset, expect, update);
}
The whole process is like this, using the CPU's CAS instruction, and using JNI to complete the Java non-blocking algorithm. Other atomic operations are done using a similar feature.
And the whole j.u.c is built on the CAs, so for synchronized blocking algorithm, J.U.C has a great improvement in performance. The resources article describes the use of CAs to build data structures such as non-blocking counters, queues, and so on.
CAS looks cool, but it can cause "ABA problems".
The CAS algorithm implements an important premise to take out the data at some point in memory, and to compare and replace it at the next moment, but any change can occur within this time difference.
For example, a thread one takes a from the memory location V, when another thread two also takes a from memory, and two does something to B, and two then turns the data in the V position into a, when the CAS operation finds that the memory is still a, and then the one operation succeeds. Although the CAS operation of thread one is successful, it does not mean that the process is not a problem. If the head of the list is changed two times, the original value is restored, but the list does not change. To solve the "ABA problem", we need to add a version number, when updating the value of the variable should not only update a variable value, but should update two values, namely the variable value and version number, Atomicstampedreference supports the atomic condition update on two variables, You can use this class for update operations.
Resources:
(1) Introduction to non-blocking algorithms
(2) Popular atoms
Transferred from: http://www.blogjava.net/xylz/archive/2010/07/04/325206.html
Java concurrency-Atomic variables and atomic operations