Java Concurrency Programming series (d)----CAs and atomic class __java

Source: Internet
Author: User
Tags cas volatile

In order to achieve thread safety, we are in front of the lock to ensure the atomic nature, then there is no lock can be implemented thread safety. It starts with the optimistic lock and the pessimistic lock.
1. Pessimistic lock. The so-called pessimistic lock, is the access to resources, by default is that there will be resource preemption, so each time to lock, only one thread to execute. Optimistic lock. Another kind of lock policy, the default resource is not competitive, multiple threads can operate at the same time, when the last update data, see whether the resource has been modified by another thread, no update, and then discard the operation. CAS

The CAS (Compare and Swap) comparison replaces, meaning
Compares the current value with a value and, if it is equal, replaces the current variable value with a new one, and discards the operation if it is not equal. ABA Issues in CAS

Assuming that thread 1 reads the variable value A, then thread 2 changes the value of the variable to B and then back to a. When the value of a variable or a is found in the thread 1 contrast, the variable is considered not modified by another thread (in fact, the A->B->A has been modified). The solution is to precede the variable with the version number, then the a->b->a becomes 1a->2b->3a.

CAS operations must be atomic operations, that is, comparison-exchange the entire process is an atomic operation, indivisible, which requires the processor to provide the corresponding instruction set to implement. A unsafe class is provided in the JDK, and the Compareandswapxxx method in the class is responsible for invoking the local method to implement the atomic operations of CAs. Atomic Class

In the previous Java Concurrency Programming series (i)-an in-depth analysis of the volatile keyword, the following increaseandget () is not an atomic operation.

Package com.rancho945.concurrent;

public class Counter {public
    int count = 0;

    public int Increaseandget () {return
        count++
    }}
}

If you want to implement an atomic operation, then I have to lock it. The JDK provides atomic classes that enable the atomic operation of the above functionality, and without locking, first take Atomicinteger as an example, compared to the counter class above

Package com.rancho945.concurrent;

Import Java.util.concurrent.atomic.AtomicInteger;


public class Test {public
    static void Main (string[] args) {
        final Atomicinteger integer = new Atomicinteger (); 
  final Counter Counter = new Counter ();
        for (int i = 0; i < i++) {
            new Thread (new Runnable () {@Override public
                void Run () {
                    //TODO auto-g enerated method stub for
                    (int j = 0; J < 100000; J + +) {
                        integer.incrementandget ();
                        Counter.increaseandget ();
                    }
                }
            ). Start ();
        }
        while (Thread.activecount () >1) {
            Thread.yield ();
        }
        System.out.println ("Atomicinteger---" +integer.get ());
        System.out.println ("Counter---" +counter.count);
    }

Execution results

Atomicinteger---2000000
Counter---1389131

You can see the implementation of the atomic class is thread-safe, but we do not lock the thread security. Atomicinteger Source Analysis

So Atomicinteger is how to achieve thread safety. Let's take a look at Atomicinteger's source.

This is the CAS operation tool class provided by JDK
private static final Unsafe Unsafe = Unsafe.getunsafe ();
The offset for the token variable,
private static final long valueoffset;
This is int values
private volatile int value;

Code blocks that are executed when the class is loaded:

static {
        try {
            valueoffset = Unsafe.objectfieldoffset
                (AtomicInteger.class.getDeclaredField ("value"));
        } catch (Exception ex) {throw new Error (ex);}
    }

The meaning here is to get the offset of the value member variable at the object's memory address, using Valueoffset to mark the location of value. Used in CAs.

Then look at the Incrementandget method:

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

Look at the Get method:

Public final int Get () {return
        value;
    }

There's nothing to talk about, then look at Compareandset ()

Public final Boolean compareandset (int expect, int update) {return
        unsafe.compareandswapint (this, Valueoffset, expect, update);
    }

Here we see that using the Unsafe.compareandswapint, the method is responsible for invoking the JNI local method to implement CAS atomic operations, where the first parameter is passed to the current object, the second parameter is the offset from the previous static code block, and the third is the expected value, If the expectation is consistent with the content of the Valueoffset offset address, this valueoffset address (note that this is the value in the Valueoffset offset address, not the valueoffset itself). Because the contents of the Valueoffset are final are updated to the value of update, returns TRUE, otherwise do not update, return FALSE.

The process is to get value first, plus 1, and then the CAS operation, if the value value and the plus 1 in the process of reading values is changed by other threads, then the CAS failed, until the success of the loop. As for other getandadd and other methods are similar, read can be analyzed by themselves. comparison of synchronized with CAS

Synchronized lock is a relatively time-consuming process, in which the performance of CAS is superior to that of synchronized in a single thread or a relatively low or general concurrency environment. But in a very high concurrency environment, if the competition for the same resource is very fierce, CAS will fail a lot. For example the atomic operation of atomic classes for (;;) The number of cyclic retries increases, and the CPU time slices consumed will increase accordingly.

It is noteworthy that the high concurrency environment does not mean competition for the same resources, such as 100 threads, competing for the same resource only a few threads, so does not mean that the thread to use synchronized must have advantages, in general, CAs are better than synchronized.

In addition, synchronized locks will suspend other threads waiting for the lock, and CAS can avoid this problem if the thread holding the lock is blocked and the other threads can only wait dryly. The optimistic lock and pessimistic lock in the reference program, as well as the hands-on implementation of optimistic lock http://www.cnblogs.com/qinggege/p/5284750.html Java concurrent programming CAs http://ifeve.com/ compare-and-swap/Chat Concurrent (v) The principle of the implementation of atomic operation Http://ifeve.com/atomic-operation/unsafe.objectFieldOffset is what. http://hllvm.group.iteye.com/group/topic/37940 Java concurrent Programming in combat Brian Goetz waiting for Dong Yunlan to translate

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.