同时从int数组快速读取/写入 [英] fast reading/writing from/to int array concurrently

查看:69
本文介绍了同时从int数组快速读取/写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种同时读取/写入int数组的快速方法。
每个索引需要写入。完成所有写操作后,仅需要
完整数组进行读取操作。

I need a fast way to read/write from/to an int array, concurrently. The write is needed per index. The reading operation is only needed for the complete array after all writes are done.

我从同步版本开始:

public final class SynchronizedIntArray {
    private final int[] elements = new int[1000000];

    public synchronized void set(int index, int value)
    {
        elements[index] = value;
    }

    public synchronized int[] getAll()
    {
        return elements;
    }
}

效果不佳。
我在网上搜索了一个更好的解决方案,并发现了AtomicIntegerArray

The performance isn't good. I searched for a better solution online and found AtomicIntegerArray

public final class ConcurrentIntArray
{
    private final AtomicIntegerArray elements = new AtomicIntegerArray(1000000);

    public void set(int index, int value)
    {
        elements.set(index, value);
    }

    public int[] getAll()
    {
        int[] intArray = new int[elements.length()];
        for (int i = 0; i < intArray.length(); i++) {
            intArray[i] = elements.get(i);
        }
        return intArray;
    }
}

但是我想知道为什么没有办法一次从
到AtomicIntegerArray的完整int数组。
性能仍然比同步版本好很多,但是
我真的需要以这种方式复制它吗?

But i am wondering why there is no method to get the complete int array from the AtomicIntegerArray at once. The performance is still much better than the synchronized version, but do i really need to copy it in this way?

对于我的问题,它比AtomicIntegerArray更快的替代方法?

Is there even a faster alternative than AtomicIntegerArray for my problem?

推荐答案

是的,您确实确实需要以这种方式进行复制。 AtomicIntegerArray 的实现意味着无法锁定整个数组并在没有其他线程同时进行更改的情况下获取它:您只能在原子上一次获取一个元素。时间。

Yes, you really do need to copy it in this way. AtomicIntegerArray's implementation means that there's no way to lock the entire array and get it without any other threads making changes at the same time: you can only atomically get one element at a time.

这篇关于同时从int数组快速读取/写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆