在Java实现的并发队列中, 实际上内部实现都使用了AtomicInteger为队列在高并发环境下计数的. java
下面是一段AtomicInteger.getAndDecrement的方法源码片断:
/** 算法
* Atomically decrements by one the current value. * * @return the previous value */ public final int getAndDecrement() { for (;;) { //获取当前值 int current = get(); //设置修改后的值 int next = current - 1; //compareAndSet: cas方法 if (compareAndSet(current, next)) //只有在正确修改值后,才返回. return current; } }
compareAndSet则调用了unsafe.compareAndSwapInt(this, valueOffset, expect, update); 安全
/** * Atomically update Java variable to <tt>x</tt> if it is currently * holding <tt>expected</tt>. * @return <tt>true</tt> if successful */ public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x);
因此最终还须要native方法的实现(即虚拟机JVM), 以后我想JVM再去CPU发送CAS操做指令. 并发
CAS算法:compareAndSet的简写, 即比较再设值. 高并发