首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中使用AtomicByteArray实现AtomicIntegerArray

在Java中使用AtomicByteArray实现AtomicIntegerArray
EN

Stack Overflow用户
提问于 2014-06-13 19:44:20
回答 1查看 744关注 0票数 0

我需要一个以AtomicByteArray的AtomicIntegerArray为模型的内存关键应用程序的AtomicIntegerArray。我的实现将四个字节封装成一个整数,并使用AtomicIntegerArray。

get()实现非常简单,和set()实现也相当简单。compareAndSwap()是比较棘手的。我的实现出现在下面(它是单线程的,很好)。

我在试着确认种族状况。一种可能的情况是,在调用get()compareAndSet()之间,值发生了更改和交换,但这似乎是无害的。

我漏掉了什么可能出错的东西吗?

代码语言:javascript
复制
/**
 * 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,它集成了下面答案中的改进。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-13 19:51:27

你可以考虑用面具。这可能会更快/更干净。

代码语言:javascript
复制
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对我们有多大的帮助。我建议你不要拿它做比较。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24212822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档