CAS and the principles outlined in the parsing Java

First, what CAS that?

       CAS (Compare And Swap), comparison and exchange, it is a CPU concurrency primitives. Its function is to determine the value of a memory location if the expected value, if it is then updated to the new value, the process is atoms.

  1 public class CASDemo {
  2     public static void main(String[] args) {
  3         AtomicInteger atomicInteger = new AtomicInteger(5);
  4 
  5         System.out.print(atomicInteger.compareAndSet(5, 2019));
  6         System.out.println(" the value are " + atomicInteger.get());
  7 
  8         System.out.print(atomicInteger.compareAndSet(5, 1024));
  9         System.out.println(" the value are " + atomicInteger.get());
 10     }
 11 }

image

       CAS concurrency primitives manifestation sun.misc.Unsafe class each method in the Java language. CAS method calls Unsafe class, JVM will help us to achieve CAS assembly instructions. This is an entirely hardware dependent function, through which implements the atomic operation, Again, since CAS is a system primitive, part of the operating system primitives language category is composed by a number of instructions for performing a a process function, execution and primitives must be continuous, not allowed to interrupt during execution, that CAS is an atomic instruction, will not cause so-called inconsistent data problems.

Two, Unsafe class

In Case of AtomicInteger atoms:

  1 public class AtomicInteger extends Number implements java.io.Serializable {
  2     private static final long serialVersionUID = 6214790243416807050L;
  3 
  4     // setup to use Unsafe.compareAndSwapInt for updates
  5     private static final Unsafe unsafe = Unsafe.getUnsafe();
  6     private static final long valueOffset;
  7 
  8     static {
  9         try {
 10             valueOffset = unsafe.objectFieldOffset
 11                 (AtomicInteger.class.getDeclaredField("value"));
 12         } catch (Exception ex) { throw new Error(ex); }
 13     }
 14 
 15     private volatile int value;
 16 
 17     // ...
 18 }

2.1 parameter parsing

  1. UnSafe CAS is the core classes. Because direct access to the underlying Java method can not, needs to be accessed by the local (Native) method, equivalent to a backdoor UNSAFE, data based on such a specific memory can be directly manipulated. Unsafe sun.misc package that class, which can be like a method of operating an internal pointer C as a direct memory operation, because the method relies on the execution of Java classes Unsafe operation in the CAS.
    Note: Unsafe class, all methods are native modified, that method Unsafe class are calling the underlying operating direct resources to perform the appropriate task.
  2. Variable valueOffset, which is variable in memory offset address is acquired as Unsafe data according to the memory address offset.
  3. Variable value with a volatile modification to ensure visibility among multiple threads.

Analytical Method Example 2.2

In getAndIncrement AtomicInteger atoms class () Example:

  . 1  / **
   2   * AtomicInteger.java class corresponds to a method of self-energizing
   . 3   * / 
  . 4  public  Final  int getAndIncrement () {
   . 5      return unsafe.getAndAddInt ( the this , valueOffset,. 1);
   . 6 }
   . 7  
  . 8  // class the Unsafe get the value of the variable specified memory area 
  . 9  public  Native  int getIntVolatile (Object var1, Long var2);
 10  
. 11  
12 is  / **
 13 is   * the Unsafe class method
 14   * @param var1 this AtomicInteger objects
 15   * @param var2 variables in memory offset address
16   * @param var4 variable increment
 17   * Analytical Method:
 18   * first call getIntVolatile () method to get the value of the variable is stored into the memory area designated var5,
 . 19   * value before the operation to be performed, and then retrieve the value from the address comparison with var5,
 20   * If the same, the value of var5 updated, and returns true, the inverse of the loop is exited, the added value returned;
 21   * If not, it returns false, the cycle continues, re-evaluated until the update success
 22 is   * / 
23 is  public  Final  int getAndAddInt (Object var1, Long var2, int var4) {
 24      int var5;
 25      do {
 26 is          var5 = the this .getIntVolatile (var1, var2);
 27     } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
 28 
 29     return var5;
 30 }

Three, CAS shortcomings

3.1 long cycle times result in cost increases

       If the CAS has acquired less than a value, it will bring a lot of overhead to the CPU.

3.2 can only guarantee the atomicity of a shared variable

       When operating the plurality of shared variables, CAS cycle can not guarantee atomicity operations, this time can be used to guarantee atomicity lock.

3.3 ABA problem

       CAS algorithm is an important prerequisite is the need to remove the data of a certain time and memory and compare replaced at the present moment, then within this time difference can lead to changes in the data.
        For example, one thread removed from the memory location V A, which is also removed when another thread A two from memory, and some of the operations performed two thread the value becomes to B, then thread turn two V position data becomes into A, this time one thread perform the operation found that CAS is still in memory A, then thread one successful operation.
        Despite the success of CAS thread one operation, but this does not mean that the process is not a problem.

       ABA to solve the problem by java.util.concurrent.atomic.AtomicStampedReference; timestamped atoms reference class to solve.

Guess you like

Origin www.cnblogs.com/lveyHang/p/11883224.html