简体   繁体   中英

Two Dimensional AtomicInteger array

Hey so I'm wondering how can I make AtomicInteger a two dimensional array, From what I've found on javadocs AtomicIntegerArray is only single dimension.

int[] newArray = new int[100];
AtomicIntegerArray atomicarray = new AtomicIntegerArray(newArray);

Which creates a AtomicIntegerArray of size 100. But I would like an atomicarray with two dimensions. I've tried doing..

AtomicInteger[][] atomicArray = new AtomicInteger[100][100];
atomicArray[00][00].set(1);

But I am met with..

java.lang.NullPointerException at nz.ac.massey.threadpool.MyClass.(MyClass.java:20)

So any ideas? thanks! :)... I haven't done much work with Atomic variables before.

if this isn't possible how can I minimic a regular primitive integer two dim array into a AtomicInteger two dim array?

Just create a one-dimensional array of length m * n , you then need a function that maps a pair of integers (i, j) to one integer. i * n + j is a good start. Assuming m is the number of rows and n the number of columns.

It is a good idea to keep all of your integers inside the AtomicIntegerArray. Or you'll have to deal with concurrency your self.

You need to instantiate all of the positions in the matrix before accessing them, something like this:

atomicArray[i][j] = new AtomicInteger();

Or this, if you want to initialize each atomic integer in a certain initial value:

atomicArray[i][j] = new AtomicInteger(initialValue);

That, for all i,j positions in the matrix. Normally you'd do this using a couple of nested for loops:

for (int i = 0; i < 100; i++) {
    for (int j = 0; j < 100; j++) {
        atomicArray[i][j] = new AtomicInteger();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM