Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AtomicBitSet implementation for java

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 existing implementation released under a licence compatible with Apache 2? I require only basic operations to set and check bits.

Edit:

The code is both performance and memory critical so I'd like to avoid synchronization or an integer per flag if possible.

like image 998
henry Avatar asked Sep 14 '12 12:09

henry


1 Answers

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;
    }
}
like image 56
Peter Lawrey Avatar answered Sep 19 '22 12:09

Peter Lawrey