我需要一个以AtomicByteArray的AtomicIntegerArray为模型的内存关键应用程序的AtomicIntegerArray。我的实现将四个字节封装成一个整数,并使用AtomicIntegerArray。
get()实现非常简单,和set()实现也相当简单。compareAndSwap()是比较棘手的。我的实现出现在下面(它是单线程的,很好)。
我在试着确认种族状况。一种可能的情况是,在调用get()和compareAndSet()之间,值发生了更改和交换,但这似乎是无害的。
我漏掉了什么可能出错的东西吗?
/**
* Atomically sets the element at position {@code i} to the given
* updated value if the current value {@code ==} the expected value.
*
* @param i the index
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public boolean compareAndSet(final int i, final byte expected, final byte val) {
int idx = i >>> 2;
int shift = (i & 3) << 3;
while (true) {
final int num = this.array.get(idx);
// Check that the read byte is what we expected
if ((byte)(num >> shift) != expected) {
return false;
}
// If we complete successfully, all is good
final int num2 = (num & ~(0xff << shift)) | ((val & 0xff) << shift);
if ((num == num2) || this.array.compareAndSet(idx, num, num2)) {
return true;
}
}
}更新:我已经实现了一个基本版本的AtomicByteArray,它集成了下面答案中的改进。
发布于 2014-06-13 19:51:27
你可以考虑用面具。这可能会更快/更干净。
int idx = i >>> 2;
int shift = (i & 3) << 3;
int mask = 0xFF << shift;
int expected2 = (expected & 0xff) << shift;
int val2 = (val & 0xff) << shift;
while (true) {
final int num = this.array.get(idx);
// Check that the read byte is what we expected
if ((num & mask) != expected2) return false;
// If we complete successfully, all is good
final int num2 = (num & ~mask) | val2;
if ((num == num2) || this.array.compareAndSet(idx, num, num2)) {
return true;
}
}您希望在循环中完成最少的工作,以便如果有争用,您可以尽可能快地再试一次。
我不确定num == num2对我们有多大的帮助。我建议你不要拿它做比较。
https://stackoverflow.com/questions/24212822
复制相似问题