In-depth understanding of java:2.3.1. Concurrent programming Concurrent Package Atomic atomic operation

Source: Internet
Author: User
Tags cas volatile

Java, there may be some scenarios, the operation is very simple, but prone to concurrency problems, such as i++,

At this point, if you rely on lock mechanism, it can lead to problems such as performance loss

Therefore, how to realize the atomic operation more simply becomes a problem that needs to be faced in Java.

Before Backport-util-concurrent was introduced into java1.5 and became JUC,

These atomic and atomic operation methods are implemented using synchronized.

However, after the advent of Juc, these atomic operations provide a new implementation based on JNI,

Like atomicinteger,atomiclong,atomicboolean,atomicreference,atomicintegerarray/atomiclongarray/. Atomicreferencearray;

These operations provide some atomization operations, such as incrementandget (equivalent to i++), Compareandset (security Assignment), and so on, the direct reading of the source code is also easy to understand.

Take Atomicinteger as an example to see how it does this:

If you are reading a value, it is simple to declare value as volatile, and you can guarantee that the data is thread-visible without a lock:

1     int value;

int get () {return value; 3}

So, what about the action of value change? To Atomicinteger implementation: ++i as an example:

 1 public final int Incrementandget () {2 for (;;) {3 int current = get (); Span style= "COLOR: #008080" >4 int next = current + 1 5 if (Compareandset (current, Next ) 6 return next; 7 }8}     

The CAs operation is used here, each time the data is read from memory and then the CAS operation is performed with the result of +1, if successful, the result is returned, otherwise it is retried until it succeeds.

And here Comparandset (Current,next), is the earlier introduction of CAs, said the dependency of the JNI implementation of optimistic locking practices:

    Boolean compareandset (intreturn Unsafe.compareandswapint (this, Valueoffset, expect, update);} 

Array atomization

Note that in Java, Atomic*array is not atomized for the entire array object (and there is no need to do so), but rather atomically an element in the group .

For example, for an integer atomic array, where the atomic method is for each element:

1Publicfinal int getanddecrement ( int i) {2 while (true3 int current = get (i); Span style= "COLOR: #008080" >4 int next = Current-1;5 if (Compareandset (I, Current, Next) 6 return current;< Span style= "COLOR: #008080" >7 }8}    /span>                

atomized operation of the reference

Does the referenced operation itself be atomic?

A reference to an object, a switch from a to B, itself does not appear non-atomic operation AH? There's nothing wrong with this idea itself,

But consider the scenario: Object A, the current execution reference A1,

Thread X expects the reference to a to be set to A2, which is A=A2,

Thread y expects the reference to a to be set to A3, which is a=a3.

x requires that a must be changed from A1 to A2, i.e. compareandset (EXPECT=A1,SETVALUE=A2);

Y requires that a must be changed from A1 to A3, i.e. Compareandset (EXPECT=A1,SETVALUE=A3).

If you strictly follow the requirements, you should have X set a reference to A2 after the Y thread operation failed, that is to say:

X:a==a1--> a=a2;

Y:A!=A1-Exception;

If it is not atomized, then y assigns a value of a to A3 directly, resulting in dirty data.

This is why the atomic reference atomicreference exists.

1      final V Getandset (v newvalue) {2            while (true) {3 V x = get ();  If (Compareandset (x, NewValue))return x; } 7}             

Note that atomicreference requires references to be volatile as well.

Updater Atomization

Several other atomic classes are atomically manipulating their own data for volatile modified basic data types,

But if a volatile variable itself already exists in the class, how do you provide atomicity?

For example, a person, which has a property of age,private volatile int age,

How do I provide atomic manipulation of age?

Private Atomicintegerfieldupdater<person> Updater = atomicintegerfieldupdater.newupdater (person.  Class, "age");  2 updater.getandincrement (5); // Add 5 years old 3 Updater.compareandset (person, year, year)// If one's age is 30, set to 35. 

Atomic Package Usage Guide in Java

Reference: http://ifeve.com/java-atomic/

In-depth understanding of java:2.3.1. Concurrent programming Concurrent Package Atomic atomic operation

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.