Atomicinteger, a class that provides atomic operations. In Java, the ++ I and I ++ operations are not thread-safe. When using them, the synchronized keyword is inevitable. Atomicinteger uses a thread-safe addition/subtraction operation interface.
Let's take a look at the interfaces provided by atomicinteger.
// Obtain the current value
Public final int get ()
// Obtain the current value and set a new value
Public final int getandset (INT newvalue)
// Obtain the current value and auto-Increment
Public final int getandincrement ()
// Obtain the current value and subtract it
Public final int getanddecrement ()
// Obtain the current value and add the expected value
Public final int getandadd (INT delta)
......
The CAS we mentioned in the previous section mainly involves the two methods.
Public final Boolean compareandset (INT exact CT, int update ){
Return unsafe. compareandswapint (this, valueoffset, exact CT, update );
}
Public final Boolean weakcompareandset (INT exact CT, int update ){
Return unsafe. compareandswapint (this, valueoffset, exact CT, update );
}
The two methods have different names, but they do the same thing. The differences may be displayed in subsequent Java versions.
For details, we can see that both interfaces call an unsafe class for operations. This is a local method implemented through JNI, and the details are not taken into consideration.
The following is a comparative test. We will write a synchronized method and a atomicinteger method to test the performance.
Package Zl. study. concurrency; <br/> Import Java. util. concurrent. atomic. atomicinteger; <br/> public class atomicintegercomparetest {<br/> private int value; </P> <p> Public atomicintegercomparetest (INT value) {<br/> This. value = value; <br/>}</P> <p> Public synchronized int increase () {<br/> return value ++; <br/>}</P> <p> Public static void main (string ARGs []) {<br/> long start = system. currenttimemillis (); </P> <p> atomicintegercomparetest test = new atomicintegercomparetest (0); <br/> for (INT I = 0; I <1000000; I ++) {<br/> test. increase (); <br/>}< br/> long end = system. currenttimemillis (); <br/> system. out. println ("time elapse:" + (end-Start); </P> <p> long start1 = system. currenttimemillis (); </P> <p> atomicinteger atomic = new atomicinteger (0); </P> <p> for (INT I = 0; I <1000000; I ++) {<br/> atomic. incrementandget (); <br/>}< br/> long end1 = system. currenttimemillis (); <br/> system. out. println ("time elapse:" + (end1-start1); </P> <p >}< br/>
Result
Time elapse: 31
Time elapse: 16
It is not difficult to see that JNI's local CAs performance far exceeds the synchronized keyword.
Reference
Http://stackoverflow.com/questions/2443239/java-atomicinteger-what-are-the-differences-between-compareandset-and-weakcompar