Multithreading series two: Atomic operations

Source: Internet
Author: User
Tags cas

What is atomic manipulation

One or a series of operations that cannot be interrupted

Ways to implement atomic operations

Java can implement atomic operations by locking and looping CAS

CAS (Compare and Swap) Why should I have CAS?

Compare and swap is an atomic operation that is compared and exchanged and is guaranteed by the Cpu at the instruction level.

Why should there be CAS: Because when atomic operations are implemented through locks, other threads must wait for the thread that has acquired the lock to run until the resource is available, which consumes a large amount of resources from the system

What parameters does CAs contain?

Cas contains three parameters: 1 v ; 2 , variable corresponds to a 3 Span style= "font-family: Arial" > We are going to modify the value of b v a b re-assigned, if not a Then do nothing and the return result of the operation is the original value.

Loops CAS: In A (dead) loop "for(;;) "in constant CAS operation until it succeeds (the spin operation is a dead loop).

CAS three major problems in implementing atomic operations

1, ABA problem: The other thread changed the value to B, quickly changed to a, the atomic operation of the thread found that the value is a to modify, so there will be problems. addressing ABA, introducing version number:1a-"2c-"3 a

2, the cycle time is very long , the CPU load is relatively large

3, the operation of a variable can be , while operating multiple shared variables a little trouble

CAS thread safety ( Surface Pilot )

Secure atomic operations with hardware-level blocking

Atomic Update base type class

Atomicboolean,Atomicinteger,atomiclong,atomicreference.

the common methods of Atomicinteger are as follows

int addandget (int delta):

boolean compareandset (int expect,int update):

int Getandincrement (): Atomic increment, but returns the value from the previous increment

Incrementandget atoms increment, but return the value after increment

int getandset (int newvalue):

1  PackageCom.lgs.atomicint;2 3 ImportJava.util.concurrent.atomic.AtomicInteger;4 5 /**6 * LGs7 * Atomic Operation update integral type8  */9  Public classAtomicinttest {Ten     StaticAtomicinteger ai =NewAtomicinteger (1); One      Public Static voidMain (string[] args) { A System.out.println (Ai.getandincrement ()); - ai.incrementandget (); - System.out.println (Ai.get ()); the     } -}

Output:

1
3

Atomic update Array class

Atomicintegerarray,atomiclongarray,atomicreferencearray

The Atomicintegerarray class essentially provides an atomic way to update the integer type in the array,

The usual methods are as follows.

int addandget (int i,int delta):

boolean compareandset (int i,int expect,int update):

Arrays are passed through the constructor method, and the class copies the array one copy, and the original array does not change.

1  PackageCom.lgs.atomicarray;2 3 ImportJava.util.concurrent.atomic.AtomicIntegerArray;4 5 /**6 * LGs7 * Atomic Operation update array8  */9  Public classAtomicarray {Ten     Static int[] Value =New int[]{1,2}; One     StaticAtomicintegerarray ai =NewAtomicintegerarray (value); A  -      Public Static voidMain (string[] args) { -Ai.getandset (0,3); theSystem.out.println (Ai.get (0)); -System.out.println (value[0]); -     } -  +}

Output:

3
1

atomically updates the class provided by the reference type.

· Atomicreference: resolves an issue that updates multiple variables

· Atomicstampedreference: Solving The ABA problem using numbers as a version care about how many people have changed

· Atomicmarkablereference: Solving The ABA problem using Boolean as a version, care is there to be modified

1  PackageCom.lgs;2 3 Importjava.util.concurrent.atomic.AtomicReference;4 5 /**6 * LGs7 * Atomic Operations Update reference types to update multiple values at the same time8  */9  Public classAtomicref {Ten  One     StaticAtomicreference<user> useratomicreference =NewAtomicreference<>(); A  -      Public Static voidMain (string[] args) { -User User =NewUser ("LGs", 26); the useratomicreference.set (user); -User UpdateUser =NewUser ("ll", 27); - Useratomicreference.compareandset (user,updateuser); - System.out.println (Useratomicreference.get (). GetName ()); + System.out.println (Useratomicreference.get (). Getold ()); -     } +  A     Static classuser{ at         PrivateString name; -         Private intOld ; -  -          PublicUser (String name,intOld ) { -              This. Name =name; -              This. Old =Old ; in         } -  to          PublicString GetName () { +             returnname; -         } the  *          Public intGetold () { $             returnOld ;Panax Notoginseng         } -     } the  +}

Output:

ll
27

Atom Update Field class

The atomic package provides the following 3 classes for atomic field updates.

· Atomicreferencefieldupdater:

· Atomicintegerfieldupdater:

· Atomiclongfieldupdater:

Violates the principle of object-oriented and generally does not use

Multithreading series two: Atomic operations

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.