`
liudunxu2
  • 浏览: 30663 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
文章分类
社区版块
存档分类
最新评论

正数原子递增选择器

 
阅读更多
原则:
1.原子性:要保证操作是原子的,线程安全的,java的atomatic包里的AtomicInteger符合这种要求
2.正数性:数字在java中是用补码进行表示的,第一位为符号位,0代表正数,1代表负数,可以对递增的数值进行与0x7FFFFFFF(int类型,4个字节)操作,保证永远为正数。当递增超过0x7FFFFFFF时,又会从0开始递增
附metaq中的实现,这个主要用在轮询的分区选择器上RoundRobinPartitionSelector,用于均匀的选择分区
/**
 * 正数的原子递增器,主要用于实现轮询
 *
 * @author apple
 *
 */
public class PositiveAtomicCounter {
    private final AtomicInteger atom;
    private static final int mask = 0x7FFFFFFF;
    public PositiveAtomicCounter() {
        atom = new AtomicInteger(0);
    }
    public final int incrementAndGet() {
        final int rt = atom.incrementAndGet();
        return rt & mask;
    }
    public int intValue() {
        return atom.intValue();
    }
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics