Atomicinteger, a class that provides an integer for atomic operations. In the Java language, ++i and i++ operations are not thread-safe and will inevitably use the Synchronized keyword when used. and Atomicinteger through a thread-safe addition and subtraction operation interface.
Look at the interface provided by Atomicinteger.
Get the current value
Public final int Get ()
Take the current value and set the new value
Public final int Getandset (int newvalue)
Gets the current value and increases itself
Public final int getandincrement ()
Get the current value and subtract
Public final int getanddecrement ()
Gets the current value and adds the expected value
Public final int getandadd (int delta)
... ...
The CAs that we mentioned in the previous section are mainly the two methods
Public final Boolean compareandset (int expect, int update) {
Return Unsafe.compareandswapint (this, valueoffset, expect, update);
}
Public final Boolean weakcompareandset (int expect, int update) {
Return Unsafe.compareandswapint (this, valueoffset, expect, update);
}
The two methods are different names, but they do the same thing, and may show differences in subsequent Java versions.
The detailed view finds that both interfaces invoke a unsafe class to operate, a local method implemented through JNI, and the details are not considered.
Here is a comparison test, we write a synchronized method and a Atomicinteger method to test, intuitive perception of the difference in performance
Package zl.study.concurrency; Import Java.util.concurrent.atomic.AtomicInteger; public class Atomicintegercomparetest {private int value, public atomicintegercomparetest (int value) {this.value = value; public synchronized int Increase () {return value++.} public static void Main (String args[]) {Long start = System.curre Nttimemillis (); Atomicintegercomparetest test = new Atomicintegercomparetest (0); for (int i=0;i< 1000000;i++) {test.increase ();} Long end = System.currenttimemillis (); System.out.println ("Time Elapse:" + (End-start)); Long Start1 = System.currenttimemillis (); Atomicinteger atomic = new Atomicinteger (0); for (int i=0;i< 1000000;i++) {atomic.incrementandget ();} Long End1 = System.currenttimemillis (); System.out.println ("Time Elapse:" + (End1-start1));}
Results
Time elapse:31
Time Elapse:16
It is not difficult to see that through JNI local CAS performance far exceed synchronized keywords
Reference
http://stackoverflow.com/questions/2443239/ Java-atomicinteger-what-are-the-differences-between-compareandset-and-weakcompar