Java Concurrency Learning Note (ix)-Atomic class Atomicinteger

Source: Internet
Author: User

Atomicinteger can guarantee that the operation of an integral type is atomic. Like i++ This operation is not atomic operation, there is a race condition, so need to lock, but the performance of locking is not high, if only to add 1 to an integer. Let's look at his realization.

    private volatile int value;

The Atomicinteger itself holds an integer variable, and all operations are based on that variable. The variable is modified by violate, which is guaranteed to be visible and visible in another blog

Java Concurrency Learning Note (vi)-Mutex and memory visibility.

Take a look at the operation of value plus 1

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

The code is nested within a for loop, and the key is in the Compareandset method. This method is managed to the Compareandswapint method of unsafe, which is supported by hardware and is atomic operation. This means that if value equals current, then value is set to Next, return true, or false to continue the next round. Why there is a value inconsistency, because in a race condition, when this thread assigns value value to current, other threads may modify the value of values, so that there is a case of inconsistency between the present and the value. Can be seen to compareandset similar optimistic lock, timely failure. In summary, the visibility of value is guaranteed by voilate, and atomic operations are guaranteed by Compareandset.

The other way, the operation is similar, all rely on compareandset to ensure


Java Concurrency Learning Note (ix)-Atomic class Atomicinteger

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.