问题描述
标准api不包括AtomicBitSet实现。我可以在AtomicIntegerArray之上滚动我自己,但也不喜欢。
The standard api does not include an AtomicBitSet implementation. I could roll my own on top of AtomicIntegerArray, but would prefer not too.
有没有人知道与Apache 2兼容的许可证下发布的现有实现?我只需要基本操作来设置和检查位。
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.
编辑:
代码是性能和内存如果可能,我想避免同步或每个标志的整数。
The code is both performance and memory critical so I'd like to avoid synchronization or an integer per flag if possible.
推荐答案
我会使用AtomicIntegerArray,每个整数使用32个标志,这将给你与BitSet相同的密度,但不需要锁线程安全。
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) / 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;
}
}
这篇关于java的AtomicBitSet实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!