Java-cas Lock-Free algorithm

Source: Internet
Author: User
Tags cas volatile

Lock

Locks are the simplest way to do concurrency, and the cost is the highest, Java Before JDK1.5 is guaranteed by the Synchronized keyword to ensure that synchronization, he is an exclusive lock, using synchronized synchronization lock for thread blocking and wake-up switching and user-state kernel state switching operation additional waste of CPU resources, locks there are other shortcomings, when a thread is waiting for the lock, It can't do anything. If a thread is delayed by holding a lock, all threads that need the lock will not be able to proceed.

CAS Lock-Free algorithm

CAS is an unlocked non-blocking algorithm, CAS is hardware-based, does not need to enter the kernel, do not need to switch threads, so you can achieve higher performance. However, in the case of serious resource competition, the probability of CAS spin is larger, thus wasting more CPU resources.

CAS is an optimistic locking technique that when multiple threads try to update the same variable simultaneously using CAS, only one of the threads can update the value of the variable, and the other threads fail, and the failed thread is not suspended, but is told that the competition has failed and can try again.

CAS (compare and exchange) are CPU instruction-level operations, with only one-step atomic operation, CAS has 3 operands, memory value V, old expected value A, new value to modify 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. CAS semantics is "I think the value of V should be a, if it is, then the value of V is updated to B, otherwise not updated, and tell V is actually how much".

The pseudo-code can be represented like this:

do{          备份旧数据;         基于旧数据构造新数据;  }while(!CAS( 内存地址,备份的旧数据,新数据 ))  

This means that when the two are compared, if they are equal, it proves that the shared data has not been modified, replaced with the new value, and then continues to run down, if not equal, that the shared data has been modified, discarded the action already done, and then re-executed the operation. It is easy to see that CAS operations are based on the assumption that shared data will not be modified, using a database-like commit-retry pattern. This assumption can lead to significant performance gains when there are few opportunities for synchronization conflicts to occur.

CAs cons

Although CAs effectively solves the problem of atomic operations, it still has three disadvantages:
1, ABA problem: Because CAS need to check before the operation of the value has not changed, if not updated. But if a value starts with a, becomes B, and becomes a, then checking with CAS will show that its value has not changed, but that is not the case.

The solution to the ABA problem is to use version numbers, such as a-b-a, into 1a-2b-3a

2, Long cycle time overhead: Spin CAS If the long time is unsuccessful, it will bring a very large execution overhead to the CPU.

3, can only guarantee a shared variable atomic operation: to a shared variable can use CAS for atomic operations, but multiple shared variables of the atomic operation will not be able to use the CAS, this time can only use locks.

Atomic operations in Java (Atomic operations)

Atomic manipulation refers to completion within one step and cannot be interrupted. Atomic operations are thread-safe in multithreaded environments without the need to consider synchronization issues. In Java, the following operations are atomic operations:

all assignments of primitive types except for long and double(基本数据类型除了long 和double)all assignments of references(引用类型)all operations of java.concurrent.Atomic* classes(原子类)all assignments to volatile longs and doubles(volatile 修饰的long 和double)

Why is a long assignment not an atomic operation? For example:

Long foo = 65465498L;

In real-time Java will be written in two steps to the long variable, first write 32 bits, then write 32 bits. This makes the thread unsafe. If you change to the following thread-safe:

private volatile long Foo;
Because the volatile interior has already done synchronized.

JVM support for CAs

Before JDK5.0, without the use of native code, you cannot write a no-wait, no-lock algorithm in the Java language. The underlying support was introduced in JDK1.5, which exposes CAS operations on types such as int, long, and object references , and the JVM compiles them into the most efficient method provided by the underlying hardware, and compiles them into corresponding machine instructions on the platform running CAs.

//JDK 8 - AtomicInteger//fetch and addpublicfinalintgetAndIncrement() {    return unsafe.getAndAddInt(this1);}//JDK7 - AtomicIntegerpublicfinalintgetAndIncrement() {    for (;;) {        intget();        int1;        if (compareAndSet(current, next))            return current;    }}

Java-cas Lock-Free algorithm

Related Article

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.