Java threads learning 10 - CAS

          And contract in such a package in Java, in java.util.concurrent.atomic, the packet is part of the data types to the Java atom package, on the basis of the original data type, an atomic operation provides methods to ensure the security thread . Below AtomicInteger, for example, to see how it is implemented.

public final int incrementAndGet() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return next;
    }
}
public final int decrementAndGet() {
    for (;;) {
        int current = get();
        int next = current - 1;
        if (compareAndSet(current, next))
            return next;
    }
}

              An example of these two methods, incrementAndGet method is equivalent atomic ++ i, decrementAndGet method of atomic equivalent --i (Chapters 1 according ++ i we know is not an atom or --i of operation), these two methods are not used in a manner to ensure the blocking of the atoms (e.g. Synchronized), which is how to ensure that the atoms of it, the following extraction CAS.

 

Compare And Swap

           CAS refers to a special instructions to support a wide range of modern CPU shared data memory to operate. This instruction will make the shared memory data read and write operations atoms.

        Simply describe the operation instructions: First, the data desired in the CPU memory will change the value to be compared. Then, when the two values are equal, the CPU will replace the value in the memory to a new value. Otherwise it would not operate. Finally, CPU will return to the old values. This series of operations are atomic. Although they may seem complicated, but it is better than the original Java 5 concurrency locking mechanism of the party. In simple terms, CAS means "I think what the original value should be, if it is, then the original value is updated to the new value, otherwise it will not be modified, and told me how much the original value." (This description is taken from "Java Concurrency in Practice")
       Simply put, CAS has three operands, memory value V, the expected value of the old A, to modify the new value of B. If and only if the expected value V A and the same memory, the memory value V modified as B, V otherwise . This is an optimistic locking of thinking, I believe it before it changes, no other threads to modify it; and Synchronized is a pessimistic lock, it thinks before it changes, there will be other threads to modify it, pessimistic locking efficiency very low. Here is a look at how to use CAS AtomicInteger atomicity operation.

volatile variable
 

private volatile int value;


       First, we declare a volatile variable value, in the second chapter we knew volatile memory to ensure the visibility of variables, that is, all the worker threads in the same time can get the same value.

public final int get() {
    return value;
}

 

Compare And Set

// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;// 注意是静态的
 
static {
  try {
    valueOffset = unsafe.objectFieldOffset
        (AtomicInteger.class.getDeclaredField("value"));// 反射出value属性,获取其在内存中的位置
  } catch (Exception ex) { throw new Error(ex); }
}
 
public final boolean compareAndSet(int expect, int update) {
  return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

               Compare and set, using this class Unsafe JNI method implemented using the CAS commands, guaranteed to be read - change - write is an atomic operation. compareAndSwapInt There are 4 parameters, this - this AtomicInteger objects, Offset - value attribute location in memory (should be emphasized that the position not value the value in memory), expect - the expected value, update - the new value, according to the above CAS during operation, when the value is equal to the value of memory expect value, then the value of the memory value is updated to update a value, and returns true, otherwise returns false. Here we need to have a good understanding of Unsafe a simple point of view from the name, insecurity, indeed, this class is used to perform low-level, non-secure operation of the collection, most of the methods in this class is direct manipulation of memory, so insecure, but when we use reflection, and contracting, are indirectly used the unsafe.

 

Set cycle
       now look at two methods mentioned at the beginning, we take incrementAndGet analyze its implementation process.

public final int incrementAndGet() {
    for (;;) {// 这样优于while(true)
        int current = get();// 获取当前值
        int next = current + 1;// 设置更新值
        if (compareAndSet(current, next))
            return next;
    }
}

         Within the loop, get the current value and set the updated value, call the CAS compareAndSet conduct operations, if successful, will return the updated value, or retry until successful. Here there may be a risk that the cycle time is too long, while the current thread is always compareAndSet, there is another thread sets the value (the idea back too), this course is a small probability that time, the current Java seemingly can not handle this case.
       

ABA

       Although the use of CAS can achieve non-blocking atomic operation, but will have a problem ABA, ABA on the issue, he plans to single out a chapter to organize.

 

Guess you like

Origin blog.csdn.net/yuhaibao324/article/details/93150039