多執行緒併發安全計數器實現限流(四)CAS
阿新 • • 發佈:2020-09-07
cas 計數器
public class CounterCAS implements Counter { volatile int i = 0; // 本質是修改記憶體中某一個變數的值 static Unsafe unsafe; private static long valueOffSet; static { try { // 反射獲取屬性 Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = (Unsafe) field.get(null); Field fieldi = CounterCAS.class.getDeclaredField("i"); valueOffSet = unsafe.objectFieldOffset(fieldi); } catch (Exception e) { e.printStackTrace(); } } public int incr() { for (; ; ) { int current = i; int update = current + 1; if(unsafe.compareAndSwapInt(this,valueOffSet, current, update)){ return update;// CAS 直接操作到記憶體層面 } } } public int decr() { for (; ; ) { // 1. 獲取i的值 int current = i; // 2. 進行計算 int update = current - 1; // CAS 近似硬體層面的操作(JDK和JVM 做的封裝) if (unsafe.compareAndSwapInt(this, valueOffSet, current, update)) { return update; } } } @Override public int get() { return i; } }