Casjava some understanding

Source: Internet
Author: User
Tags cas lock queue

How to implement shared data access without locking mechanisms. (Do not use locks, do not use sychronized blocks or methods, and do not work directly with the thread security provided by the JDK
Data structure, you need to implement a class to ensure that multiple threads concurrently read and write the shared data in this class is thread-safe, what to do? )

A common method of non-locking programming: Hardware CPU Synchronization Primitives CAS (Compare a
nd Swap), such as no lock stack, no lock queue (concurrentlinkedqueue), and so on. Right now
Almost all CPU instructions support CAS Atomic operations, and X86 corresponds to CMPXCHG sinks.
The CMPXCHG instruction that the processor executes is an atomic operation. With this atomic operation,
We can use it to implement a variety of lock free data structures.
CAS implements an optimistic lock that differs from the sychronized synchronization lock when multiple threads try to make
When you update the same variable with CAS, only one of the threads can update the value of the variable, while the other lines
Fail, the failed thread is not suspended, but is told that the competition has failed and can
Try it again. The CAS has 3 operands, a memory value of V, an old expected value of A, and a new value, B, to be modified.
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.
In fact, CAS is also a lock operation, but is triggered by the CPU, than synchronized performance
It's much better. The key point of CAS is that the system guarantees the atomicity of the comparison and exchange operations at the hardware level,
The processor uses a method based on cache lock or bus lock to implement atomic operation between multiple processors.
For A common implementation of CAS non-blocking algorithms.

A common implementation of CAS non-blocking algorithms.
A variable that is shared among threads, first in main memory, and then each thread's work
Memory will also retain a copy. The expected value here is the copy of the thread reservation. When the thread is from
When the value of the variable is obtained in main memory, the variable may have been flushed by another thread in main memory, but the
The variable is still the original value in the thread's working memory, which is called the expected value. When you want to use CAS
When this value is refreshed, if the thread's working memory is found to be inconsistent with main storage, it will fail if
Consistent, you can update the success.
The Atomic package provides a series of atomic classes. These classes can guarantee a multi-threaded environment when a
When a thread executes a atomic method, it is not interrupted by another thread, and the other thread is like a spin lock
Wait until the execution of the method is complete before the JVM chooses a thread from the wait queue to execute.
The Atomic class is non-blocking at the software level, and its atomicity is actually at the hardware level with the help of relevant
Instructions to ensure that.
Atomicinteger is an Integer class that supports atomic operations, which is guaranteed to
The increment and decrease of the Atomicinteger type variable is atomic and does not appear under multiple threads
Data inconsistency issues. If you do not use Atomicinteger, you want to implement a sequentially acquired

ID, the lock operation must be performed on each fetch to avoid obtaining the same ID when concurrency occurs
The phenomenon. The atomicxxx classes in Java concurrency libraries are based on the implementation of this primitive, taking out
Atomicinteger to study how the data is correct without a lock:
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 data and the +1
The result is a CAS operation that returns results if successful, or retries until successful.
Compareandset uses JNI to complete the operation of CPU instruction, non-blocking algorithm.
Public final Boolean compareandset (int expect, int update) {
Return Unsafe.compareandswapint (this, valueoffset, expect,
Update);
}
where Unsafe.compareandswapint () is a native method that calls
The CAS primitive completes the operation.
First assume that there is a variable i,i initial value of 0. Each thread has a +1 operation on I. Cas
This is guaranteed to be synchronous:
Assuming there are two threads, thread 1 reads in memory with a value of 0,current = 0,next = 1, and then
After suspending, then thread 2 operates on I, which changes the value of I to 1. Thread 2 finishes, back to line
Process 1, enter the IF in the Compareandset method, the logic of the operation of the method is, (1)
Returns true if the value of the operand is not modified in memory, and then the Compareandset method
Returns the value of next (2) if the value of the operand has been modified in memory, it returns false and re-
Go to the next loop, re-get current value of 1,next to 2, and then compare,
Since this time has not been modified, so the direct return 2.
So why do self-increment operations go through CAS? Careful observation
The Incrementandget () method finds that the self-increment operation is actually split into two steps:
int current = get ();
int next = current + 1;
Because volatile can only guarantee that the most recent value is read or written, the following conditions may occur:
1.A thread performs a get () operation to get the current value (assuming 1)

2.B thread performs a get () operation to get the current value (1)
3.B thread Execution Next = current + 1 operation, next = 2
4.A thread Execution Next = current + 1 operation, next = 2
The result is obviously not what we want, so the self-increment operation must be done using CAS.
Advantages and disadvantages of CAS
CAS is guaranteed atomicity at the hardware level, does not lock the current thread, and its effectiveness
The rate is very high.
Although CAS is very efficient in implementing atomic operations, it still has three problems.
1, ABA problem. CAS checks if the value has changed while operating the value, without changing the case
Will not be updated. But if a value turns into a, B, and a, then CAS does
The check will assume that the value has not changed and the operation was successful. The solution to the ABA problem is to use the version number.
Append the version number before the variable, and add one to the version number each time the variable is updated, then a-b-a
It becomes 1a-2b-3a. A class is provided in the atomic package that starts the JDK from Java1.5.
Atomicstampedreference to solve the ABA problem. Starting with the Java1.5 JDK
The atomic package provides a class atomicstampedreference to solve the ABA problem. This
The Compareandset method of a class is to first check whether the current reference is equal to the expected reference, and
And if the current flag is equal to the expected flag, and if all is equal, the reference and the label are atomically
The value of the log is set to the given update value.
An important premise of CAS algorithm implementation is to take out the data at some point in memory, and in the next
Compare and replace the extracted data with the original data in memory, the time difference will cause
Changes in the data.
For example, a thread one removes a from the memory location V, and another thread two
In memory, a is removed, and a number of the actions are changed to B, and then the V position is
It becomes a, when thread one carries out CAS operations and discovers that memory is still a,
Success. Although the CAS operation of thread one is successful, it does not mean that the process is no problem
Of If the head of the list is changed two times, the original value is restored, but the list does not change.
So the atomic operations mentioned earlier
Atomicstampedreference/atomicmarkablereference is very useful. This allows
Allows a pair of changed elements to operate atomically.

The hidden danger of the  aba problem is that the implementation of various optimistic locks often uses version
number versions to mark records or objects, avoiding problems caused by concurrent operations. In Java,
Atomicstampedreference<e> also implements this function by wrapping the tuple of [E,integer]
to mark the object's version stamp stamp, thus avoiding the ABA problem.
2, long cycle time overhead. Spin CAS can cause very large
execution overhead for the CPU if it is unsuccessful for a long time. CAS are therefore not suitable for scenarios where competition is very frequent.
3. Only one atomic operation of a shared variable can be guaranteed. When performing operations on a shared variable, we can
use circular CAS to guarantee atomic operations, but when working with multiple shared variables, the loop
CAS cannot guarantee the atomicity of the operation, which can be done with locks.
Paste here a counter that simulates the CAS implementation:
public class Cascount implements Runnable {
Private Similatedcas counter = new SIMILATEDCA S ();
public void Run () {
for (int i = 0; i < 10000; i++) {
System.out.println (this.increment ());
}
}

public int increment () {
int oldValue = Counter.getvalue ();
int newvalue = OldValue + 1;
while (!counter.compareandswap (OldValue, NewValue)) {//
If the CAs fails, go to the new value to continue with the CAs
OldValue = Counter.getvalue ();
NewValue = OldValue + 1;
}
return newvalue;
}
public static void Main (string[] args) {
Runnable run = new Cascount ();
New Thread (Run). Start ();
New Thread (Run). Start ();
New Thread (Run). Start ();
New Thread (Run). Start ();
New Thread (Run). Start ();
}
}
Class Similatedcas {
private int value;
public int GetValue () {
return value;
}
This can only be used synchronized, after all, cannot invoke the operating system's CAS
Public synchronized Boolean compareandswap (int expectedvalue,
int newvalue) {
if (value = = Expectedvalue) {
value = newvalue;
return true;
}
return false;
}
}

Casjava some understanding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.