java-Multithreading in-depth (v) Atomic analysis

Source: Internet
Author: User

(i) Use of atomic

The Atomic Atom package is available in java.util.concurrent to enable Atomic operations (atomic operation), in which operations performed in a multithreaded environment are not interrupted by other threads.

/** * Atomic Simple demo *  * @author peter_wang * @create-time 2014-6-9 Morning 9:29:58 */public Class atomicdemo    extends Thread {    private static final Atomicinteger Test_int = new Atomicintege  R ();    @Override     public void run () {        Test_int.incrementandget ();   }   /**     * @param args     */    public static void main (STR Ing[] args) {        for (int i = 0; i < i++) {            Atom Icdemo demo = new Atomicdemo ();            Demo.start ();          & nbsp  Try {                Demo.join ();           }            catch (interruptedexception e) {              &NBSP ; E.printstacktrace (); &nbSp          }       }              &NB Sp SYSTEM.OUT.PRINTLN ("Final result:" +test_int);   }}

Operation Result:

Final Result: 1000

Multiple threads self-increment a variable of type Atomicinteger, and the result of the operation is correct. If you use the normal int variable, i++ multithreaded operations can result in errors.

(ii) Principle analysis

SOURCE Analysis:

Incrementandget function

/** * atomically increments by one of the current     value.     *     * @return The updated value */public    final int incrementandget () {for        (;;) {            //Gets the current value            int = = Get ();            int next = current + 1;            Loop execution to incremental success            if (Compareandset (current, next))                return next;        }    }
private volatile int value;
value is a volatile type that ensures that this thread can get the latest value.

Method continuously obtains the value and increments the operation until the operation succeeds.

Public final Boolean compareandset (int expect, int. update) {return Unsafe.compareandswapint (this, valueoffset, expect, up date);    }
Compareandset calling native native method CAs (compareandset) using unsafe increments the value.

(iii) CAS brief

CAS uses CPU calls to implement the underlying directives.

A single processor, for simple read and write operation, can guarantee the atomic nature of its own read, multi-processor or complex memory operation, CAS using bus lock or cache lock mode to ensure atomicity.

1. Bus Plus lock

such as i=0 initialization, multi-processor multithreaded environment under i++ operation, processor A and B simultaneously read the I value to their respective caches, respectively, the write-back value i=1 the same. The processor provides a lock# signal, after the bus lock, processor a reads I value and increments, processor B is blocked cannot read I value.

2. Cache Lock

Bus lock, under the lock# signal, other threads can not operate memory, poor performance, cache lock can better deal with the problem.

Cache lock, processor A and B read the I value to the cache at the same time, processor A is incremented in advance, the data is immediately written back to the main memory, and the processor B caches the data, and processor B needs to reread the I value.



java-Multithreading in-depth (v) Atomic analysis

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.