Java Multi-thread CAs

Source: Internet
Author: User
Tags cas


In Java and the contract has such a package, java.util.concurrent.atomic, the package is the Java part of the data type of atomic encapsulation, on the basis of the original data type, provides an atomic operation method, to ensure thread safety. Take Atomicinteger, for example, to see how it is implemented.

Public final int Incrementandget () {for    (;;) {        int current = Get ();        int next = current + 1;        if (Compareandset (current, next))            return next;}    }

Public final int Decrementandget () {for    (;;) {        int current = Get ();        int next = current-1;        if (Compareandset (current, next))            return next;}    }

Taking these two methods as an example, the Incrementandget method is equivalent to the atomicity of the ++i,decrementandget method equivalent to the atomicity of the-I (according to the first chapter and the second chapter we know that ++i or-I is not an atomic operation), Neither of these methods uses a blocking approach to ensure atomicity (such as synchronized), how do they guarantee atomicity, and the following leads to CAS.

Compare and Swap

CAS refers to a special instruction that is widely supported by modern CPUs in the operation of shared data in memory. This instruction will perform atomic read and write operations on the shared data in memory. briefly describe the operation of this instruction: first, the CPU compares the data that will be changed in memory with the expected value. Then, when the two values are equal, the CPU replaces the values in memory with the new values. Otherwise, do not do the operation. Finally, the CPU returns the old value. This series of operations is atomic. Although seemingly complex, they are the root of the Java 5 concurrency mechanism, which is superior to the original locking mechanism. Simply put, the meaning of CAS is "What I think the original value should be, if it is, update the original value to a new value, otherwise do not modify, and tell me what the original value is." (this description is quoted from the Java Concurrency Programming practice)
Simply put, 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 both the expected value A and the memory value v are the same, the memory value V is modified to B, otherwise V is returned. This is an optimistic locking idea, it is believed that before it modifies, there is no other thread to modify it, and synchronized is a pessimistic lock, it is believed that before it changes, there must be other threads to modify it, pessimistic lock efficiency is very low . Let's take a look at how Atomicinteger uses CAs for atomic operations.

The ABA problem in CAs

So-called, the problem is basically like this:

    1. Process P1 reads a value of a in a shared variable
    2. P1 was preempted, process P2 executed.
    3. P2 the value of the shared variable from a to B, and then to a, at this time by P1 preemption.
    4. P1 returned to see that the value in the shared variable was not changed, and then continued.

Although P1 thought that the value of the variable did not change, it continued to execute, but this raises some potential problems. The ABA problem is most likely to occur in the lock free algorithm, with CAs taking the brunt because CAS determines the address of the pointer. If this address is reused, the problem is huge. (address reuse occurs very often, a memory allocation is released, redistributed, most likely the original address)

such as the dequeue () function above, because we want to separate head and tail, so we introduced a dummy pointer to head, when we do the CAS, if the head of the memory is recycled and reused, and the memory of Reuse is Enqueue () came in, This is going to be a big problem. ( reusing memory in memory management is basically a very common behavior. )

You may not understand this example, and Wikipedia gives a living example

You took a suitcase full of money at the airport, and here comes a hot sexy beauty, and then she is very warm tease you, and when you do not notice, the same suitcase and your full of money in the box to a bag, and then left, you see your suitcase is still there, So he was carrying a suitcase to catch the plane.

This is the problem of ABA.

Excerpt from:

Java Multi-thread CAs

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: 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.