Java Implements atomic operations
What is CAs
Compare and swap Compare and swaps
CAS operations need to enter two numeric values, an old value (the value before the expected operation) and a new value, in the operation period before comparing the old value has not changed, if not changed, only to replace the new value, the change is not exchanged.
Atomic operation with cyclic CAS
CAS operations in the JVM are implemented using the CMPXCHG instructions provided by the processor.
The basic idea of the spin CAS implementation is to cycle through the CAS operation until successful , the following code implements a CAS thread-safe counter method Safecount and a non-thread-safe counter count.
package com.usoft;import java.util.arraylist;import java.util.list;import Java.util.concurrent.atomic.atomicinteger;public class counter { private atomicinteger atomici = new atomicinteger (0); private Int i = 0; public static void main (String[] args) { final Counter cas = new Counter (); list<thread> ts = new Arraylist<thread> (; long start = ) System.currenttimemillis (); for (int j = 0; j < 100; j++) { thread t = new threaD (new runnable () { @Override public void run () { for (int i = 0; i < 10000; i++) { cas.count (); cas.safecount (); } } }); ts.add (t); } for (thread t : ts) { t.start (); } // wait for all threads to complete for (thread t : ts) { try { t.join (); } catch (interruptedexception e) { e.Printstacktrace (); } } system.out.println (CAS.I); system.out.println (Cas.atomicI.get ()); system.out.println (System.currenttimemillis () - start); } /** * using CAs to implement thread safety counters */ private void safecount () { for (;;) { int i = Atomici.get (); boolean suc = atomici.compareandset (i, ++i); if (SUC) { break; } } } /** * Non-thread safety counter */ private void count () { i++; }}
There are some concurrency frameworks in Java and bundles that also use spin CAs to implement atomic operations, such as the Xfer method of the LinkedTransferQueue class. CAS is an efficient solution to atomic operations, but CAS still has three major problems. ABA problem, the long cycle time overhead and the only guarantee of a shared variable atomic operation.
ABA problem. Because CAs needs to check that the value is not changed when the value is manipulated, if it does not change, it is updated, but if a value is a, B, and a, then checking with CAS will show that its value has not changed, but actually it has changed. The solution to the ABA problem is to use the version number. Append the version number before the variable, and add one to the version number each time the variable is updated, then A-b-a will become 1a-2b-3a.
A class atomicstampedreference is provided in the atomic package of the JDK starting with Java1.5 to solve the ABA problem. The Compareandset method of this class is to first check whether the current reference is equal to the expected reference, and whether the current flag is equal to the expected flag, and if all is equal, then atomically sets the reference and the value of the flag to the given update value.
public Boolean Compareandset
(V expectedreference,//Expected reference
V newreference,//updated references
int Expectedstamp,//expected flag
int newstamp)//post-update flag
Long cycle time overhead. Spin CAs can cause very large execution overhead for CPUs if they are unsuccessful for a long time. If the JVM can support the pause instruction provided by the processor then the efficiency will be improved, the pause command has two functions, first it can delay the pipelining instruction (de-pipeline), so that the CPU does not consume excessive execution resources, the delay depends on the specific implementation of the version, On some processors, the delay time is zero. Second, it avoids the CPU pipelining being emptied (CPU pipeline flush) when exiting the loop due to memory order collisions (violation), which improves CPU execution efficiency.
Only atomic operations of a shared variable can be guaranteed. When performing operations on a shared variable, we can use the method of circular CAs to guarantee atomic operations, but for multiple shared variables, the cyclic CAS cannot guarantee the atomicity of the operation, it is possible to use locks at this time, or there is a trickery way to combine multiple shared variables into a single shared variable to operate. For example, there are two shared variable i=2,j=a, merge ij=2a, and then use CAs to manipulate IJ. Starting with Java1.5 The JDK provides the Atomicreference class to guarantee atomicity between reference objects, and you can put multiple variables in an object for CAS operations.
Atomic operation with lock mechanism
The lock mechanism ensures that only the thread that obtains the lock can manipulate the locked memory area. There are many kinds of locking mechanisms inside the JVM, there are biased locks, lightweight locks and mutexes, it is interesting that in addition to biased locks, the JVM implements the way the lock is used by the cyclic CAs, when a thread wants to enter the synchronization block using a circular CAs method to obtain the lock, when it exits the synchronization block using a circular CAS release lock. Refer to synchronized in the article Java SE1.6 for detailed instructions.
Http://www.infoq.com/cn/articles/java-se-16-synchronized
=======end=======
Java Implements atomic operations