AtomicBitSet implementation for java

前端 未结 2 462
鱼传尺愫
鱼传尺愫 2020-12-16 11:46

The standard api does not include an AtomicBitSet implementation. I could roll my own on top of AtomicIntegerArray, but would prefer not too.

Is anyone aware of an e

相关标签:
2条回答
  • 2020-12-16 12:33

    I would use an AtomicIntegerArray and I would use 32 flags per integer which would give you the same density as BitSet but without needing locks for thread safety.

    public class AtomicBitSet {
        private final AtomicIntegerArray array;
    
        public AtomicBitSet(int length) {
            int intLength = (length + 31) >>> 5; // unsigned / 32
            array = new AtomicIntegerArray(intLength);
        }
    
        public void set(long n) {
            int bit = 1 << n;
            int idx = (int) (n >>> 5);
            while (true) {
                int num = array.get(idx);
                int num2 = num | bit;
                if (num == num2 || array.compareAndSet(idx, num, num2))
                    return;
            }
        }
    
        public boolean get(long n) {
            int bit = 1 << n;
            int idx = (int) (n >>> 5);
            int num = array.get(idx);
            return (num & bit) != 0;
        }
    }
    
    0 讨论(0)
  • 2020-12-16 12:35

    Look at http://www.javamex.com/tutorials/synchronization_concurrency_7_atomic_integer_long.shtml

    Not exactly using BitSet, but AtomicInteger.

    0 讨论(0)
提交回复
热议问题