5 Nisan 2022 Salı

AtomicIntegerArray Sınıfı

Giriş
Şu satırı dahil ederiz
import java.util.concurrent.atomic.AtomicIntegerArray;
AtomicLongArray sınıfı da benzer işlev görür. Açıklaması şöyle
Provides atomic operations for arrays of int variables. It has the same methods as AtomicInteger but has an “index” in its signature. You can not change the size of the array after the AtomicIntegerArray was created.

Kullanım Durumu
Açıklaması şöyle
Noncompliant Code Example (Arrays)
Values assigned to an array element by one thread—for example, by calling setFirst()—might not be visible to another thread calling getFirst() because the volatile keyword guarantees safe publication only for the array reference; it makes no guarantee regarding the actual data contained within the array.

This problem arises when the thread that calls setFirst() and the thread that calls getFirst() lack a happens-before relationship. A happens-before relationship exists between a thread that writes to a volatile variable and a thread that subsequently reads it. However, setFirst() and getFirst() read only from a volatile variable—the volatile reference to the array. Neither method writes to the volatile variable.

Compliant Solution (AtomicIntegerArray)
To ensure that the writes to array elements are atomic and that the resulting values are visible to other threads, this compliant solution uses the AtomicIntegerArray class defined in java.util.concurrent.atomic.
getAndIncrement metodu
Örnek
Şöyle yaparız
final int arrayLength = 5;
AtomicIntegerArray atomicIntArray = new AtomicIntegerArray(arrayLength);

Runnable incrementTask = () -> {
  for (int i = 0; i < arrayLength; i++) {
    int previousValue = atomicIntArray.getAndIncrement(i);
    System.out.println("Incremented index " + i + ": " + previousValue 
      + " to " + (previousValue + 1));
  }
};

Thread thread1 = new Thread(incrementTask);
Thread thread2 = new Thread(incrementTask);

thread1.start();
thread2.start();

try {
  thread1.join();
  thread2.join();
} catch (InterruptedException e) {
  e.printStackTrace();
}

System.out.println("Final Array: " + atomicIntArray.toString());
get ve set metodu
Örnek
Şöyle yaparız
final class Foo {
  private volatile int[] arr = new int[20];
 
  public int getFirst() {
    return arr[0];
  }
 
  public void setFirst(int n) {
    arr[0] = n;
  }
 
  // ...
}

class Foo {
  private final AtomicIntegerArray atomicArray = new AtomicIntegerArray(20);
 
  public int getFirst() {
    return atomicArray.get(0);
  }
 
  public void setFirst(int n) {
    atomicArray.set(0, 10);
  }
 
  // ...
}