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中的一段初始化代码:
// 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源代码,暂且不做详论,待阅读后再增加本文内容。