使用AtomicIntegerArray在Java中实现AtomicByteArray

使用AtomicIntegerArray在Java中实现AtomicByteArray,java,concurrency,atomic-values,Java,Concurrency,Atomic Values,我需要一个原子字节数组,用于模仿Java的内存关键型应用程序。我的实现将四个字节包装成一个整数,并使用AtomicIntegerArray get()实现非常简单,而和set()实现非常简单。compareAndSwap()比较棘手。我的实现如下所示(它在单线程中工作得很好) 我正试图确定比赛状态。一种可能的情况是,在调用get()和compareAndSet()之间,值发生了更改并交换回来,但这似乎是无害的 我是否遗漏了任何可能出错的内容 /** * Atomically sets the

我需要一个原子字节数组,用于模仿Java的内存关键型应用程序。我的实现将四个字节包装成一个整数,并使用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;
        }
    }
}
/**
*原子地将{@code i}位置的元素设置为给定的
*如果当前值{@code=}超过预期值,则更新值。
*
*@param i索引
*@param预期为预期值
*@param更新新值
*@成功返回true。假返回表示
*实际值不等于预期值。
*/
公共布尔比较数据集(最终整数i,预期的最终字节,最终字节val){
int idx=i>>>2;
int shift=(i&3)>shift)!=预期值){
返回false;
}
//如果我们成功完成,一切都很好

最后的int NUM2=(num & ~(0xff),您可以考虑使用一个掩码。这可能更快/更干净。

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;
    }
}
intidx=i>>2;

int shift=(i&3)我将
i/4
->
i>>2
8*(i%4)
->
(i&3)这是否属于?PeterLawrey谢谢你的建议。修订版。@JimGarrison我不知道,但我很乐意在那里重新发布。这更像是一个并发问题,而不是Java代码问题。这就是为什么我要求结束主题而不是投票。我很好奇这类问题属于哪里。谢谢!我建议了一些与sig相关的更正ning和byte-to-int进行升级。具体来说,当您对-1(0xff)执行位操作时,它首先升级为int-1(0xfffffff)。我实现了一个基本版本,它在