Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fast reading/writing from/to int array concurrently

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.

I started with a synchronized version:

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;
    }
}

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;
    }
}

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?

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

like image 960
coder Avatar asked Nov 21 '25 03:11

coder


1 Answers

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.

like image 183
Louis Wasserman Avatar answered Nov 22 '25 15:11

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!