说起JAVA并发编程,就不得不聊聊CAS(Compare And Swap)和AQS了(AbstractQueuedSynchronizer)。
CAS(Compare And Swap)
什么是CAS
CAS(Compare And Swap),即比较并交换。是解决多线程并行情况下使用锁造成性能损耗的一种机制,CAS操作包含三个操作数——内存位置(V)、预期原值(A)和新值(B)。如果内存位置的值与预期原值相匹配,那么处理器会自动将该位置值更新为新值。否则,处理器不做任何操作。无论哪种情况,它都会在CAS指令之前返回该位置的值。CAS有效地说明了“我认为位置V应该包含值A;如果包含该值,则将B放到这个位置;否则,不要更改该位置,只告诉我这个位置现在的值即可。
// 获取当前值current,并设置新值为current+1 publicfinalintgetAndIncrement(){ for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return current; } }
To use this class as the basis of a synchronizer, redefine the * following methods, as applicable, by inspecting and/or modifying * the synchronization state using {@link #getState}, {@link * #setState} and/or {@link #compareAndSetState}: * * <ul> * <li> {@link #tryAcquire} * <li> {@link #tryRelease} * <li> {@link #tryAcquireShared} * <li> {@link #tryReleaseShared} * <li> {@link #isHeldExclusively} * </ul>
// 覆盖在共享模式下尝试释放锁 protectedbooleantryReleaseShared(int releases){ // 在for循环中Decrement count直至成功; // 当状态值即count为0的时候,返回false表示 signal when transition to zero for (;;) { int c = getState(); if (c == 0) returnfalse; int nextc = c-1; if (compareAndSetState(c, nextc)) return nextc == 0; } } }
privatefinal Sync sync;
// 使用给定计数值构造CountDownLatch publicCountDownLatch(int count){ if (count < 0) thrownew IllegalArgumentException("count < 0"); this.sync = new Sync(count); }