AtomicIntegerの実用的な使い方 質問する

AtomicIntegerの実用的な使い方 質問する

AtomicInteger やその他の Atomic 変数では同時アクセスが許可されていることは理解しています。しかし、このクラスは通常どのような場合に使用されるのでしょうか?

ベストアンサー1

の主な用途は 2 つありますAtomicInteger

  • incrementAndGet()多数のスレッドで同時に使用できるアトミックカウンタ(など)として

  • サポートするプリミティブとして比較と交換compareAndSet()非ブロッキングアルゴリズムを実装するための命令( )。

    以下は、非ブロッキング乱数ジェネレータの例です。Brian Göetz の Java 並行処理の実践:

    public class AtomicPseudoRandom extends PseudoRandom {
        private AtomicInteger seed;
        AtomicPseudoRandom(int seed) {
            this.seed = new 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;
                }
            }
        }
        ...
    }
    

    ご覧のとおり、基本的には とほぼ同じように動作しますがincrementAndGet()、増分ではなく任意の計算 ( calculateNext()) を実行します (そして、返す前に結果を処理します)。

おすすめ記事