/ Java  

Java Multithreading 11: AtomicIntegerArray

AtomicIntegerArray, AtomicLongArray, and AtomicReferenceArray are similar in principle and usage. In this blog let’s take a look at it.

AtomicInteger is used to perform atomic operations on integers. AtomicIntegerArray is to perform atomic operations on integer arrays.

Some main method list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Create a AtomicIntegerArray with given length
AtomicIntegerArray(int length)

// Create a AtomicIntegerArray with the same length as int[] array
AtomicIntegerArray(int[] array)

// Add delta to element at index i
int addAndGet(int i, int delta)

// Increase element at index i by 1
int incrementAndGet(int i)

// Decrease element at index i by 1
int decrementAndGet(int i)

// Get value of element at index i
int get(int i)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class IntArrayTest {
public static void main(String[] args){
int[] arrInt = new int[] {10, 20, 30, 40, 50};
AtomicIntegerArray aia = new AtomicIntegerArray(arrInt);

aia.set(0, 100);

for (int i = 0, len = aia.length(); i < len; i++) {
System.out.printf("get(%d) : %s\n", i, aia.get(i));
}

System.out.printf("%20s : %s\n", "getAndDecrement(0)", aia.getAndDecrement(0));
System.out.printf("%20s : %s\n", "decrementAndGet(1)", aia.decrementAndGet(1));
System.out.printf("%20s : %s\n", "getAndIncrement(2)", aia.getAndIncrement(2));
System.out.printf("%20s : %s\n", "incrementAndGet(3)", aia.incrementAndGet(3));
System.out.printf("%20s : %s\n", "addAndGet(100)", aia.addAndGet(0, 100));
System.out.printf("%20s : %s\n", "getAndAdd(100)", aia.getAndAdd(1, 100));

System.out.printf("%20s : %s\n", "compareAndSet()", aia.compareAndSet(2, 31, 1000));
System.out.printf("%20s : %s\n", "get(2)", aia.get(2));

}
}

Result:

1
2
3
4
5
6
7
8
9
10
11
12
13
get(0) : 100
get(1) : 20
get(2) : 30
get(3) : 40
get(4) : 50
getAndDecrement(0) : 100
decrementAndGet(1) : 19
getAndIncrement(2) : 30
incrementAndGet(3) : 41
addAndGet(100) : 199
getAndAdd(100) : 19
compareAndSet() : true
get(2) : 1000