Friday, March 18, 2016

[Java] CAS Compare and Swap

http://www.blogjava.net/xylz/archive/2010/07/04/325206.html
http://blog.hesey.net/2011/09/resolve-aba-by-atomicstampedreference.html
http://www.searchsoa.com.cn/showcontent_69238.htm
http://ifeve.com/atomic-operation/
http://www.infoq.com/cn/articles/java-memory-model-5

java.util.concurrent use CAS to realize a non-blocking lock which is different from synchronous

CAS has 3 operations: 

  1. value v
  2. old expected value A
  3. new expected value B
only if V == A, then replace A with B

 Non-blocking

one thread's Pending or Failure will not influence the other threads.
(Modem CUP has special instructions to update shared data and detecting the influence of other threads; CAS use this to replace the lock for synchronization)

Ex : AtomicInterger 
  •  private volatile int value;
  •  public final int get() {
            return value;
        }
  •  ++i : 
    • public final int incrementAndGet() {
          for (;;) {
              int current = get();
              int next = current + 1;
              if (compareAndSet(current, next))
                  return next;
          }
      }
  • "而compareAndSet利用JNI来完成CPU指令的操作。
    public final boolean compareAndSet(int expect, int update) {  
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
        }
    整体的过程就是这样子的,利用CPU的CAS指令,同时借助JNI来完成Java的非阻塞算法。其它原子操作都是利用类似的特性完成的。"


No comments:

Post a Comment