从atomicInteger看concurrent

 private AtomicInteger seed;
public int nextInt(int n) {
        while (true) {
            int s = seed.get();
            int nextSeed = calculateNext(s);
            if (seed.compareAndSet(s, nextSeed)) {
                int remainder = s % n;
                return remainder > 0 ? remainder : remainder + n;
            }
        }
    }
seed.compareAndSet方法把传统的get,set方法调用之间的黑色区域时间给抹掉了。和blockingQueue中的putIfAbsent方法有殊途同归之妙。

引入AtomicInteger中的一段初始化代码: java

// 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"));
      } catch (Exception ex) { throw new Error(ex); }
    }

这有篇文章描述unsafe类,但我如今没有拿到Unsafe源代码,暂且不作详论,待阅读后再增长本文内容。 code

相关文章
相关标签/搜索