Atomicinteger, a class that provides an integer for atomic manipulation. In the Java language, ++i and i++ operations are not thread-safe and, when used, will inevitably use the Synchronized keyword. The Atomicinteger is a thread-safe plus-minus operation interface.
Look at the interfaces provided by Atomicinteger.
Gets 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 self-increment
Public final int getandincrement ()
To get the current value, and to subtract from the
Public final int getanddecrement ()
Gets the current value, plus the expected value
Public final int getandadd (int delta)
... ...
The CAs we mentioned in the previous section are mainly these 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 the same thing is done, and may show a difference in the subsequent Java version.
Detailed review will find that both interfaces are called an unsafe class to operate, this is a local method implemented by JNI, the details are not considered.
Here is a comparison test, we write a synchronized method and a Atomicinteger method to test, intuitively feel the difference in performance
[Java] view plaincopy
-
Package zl.study.concurrency;
-
Import Java.util.concurrent.atomic.AtomicInteger;
-
public class atomicintegercomparetest {
-
Private int value;
-
-
public Atomicintegercomparetest ( int
-
This . value = value;
-
}
-
-
public synchronized int increase () {
-
return value++;
-
}
-
-
public static void
-
Long start = System.currenttimemillis ();
-
-
Atomicintegercomparetest test = new atomicintegercomparetest (0);
-
for( inti=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( inti=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 the local CAS performance by JNI is far beyond the synchronized keyword
Reference
http://stackoverflow.com/questions/2443239/ Java-atomicinteger-what-are-the-differences-between-compareandset-and-weakcompar
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Multithreaded programming model for Java 5--starting from Atomicinteger