Giriş
Şu satırı dahil ederiz
import java.util.concurrent.atomic.AtomicStampedReference;
Açıklaması şöyle
Provides atomic operations for stamped reference variables. Same as AtomicMarkableReference but here we have an integer as “additional information” instead of boolean.
ABA problem'i için kullanılır. Açıklaması şöyle
The ABA problem arises when a value of a shared variable changes from A to B and then back to A again, making it difficult to detect certain concurrent changes. Consider the following scenario:1. Initially, a shared variable `value` is set to A.2. Thread 1 reads the value of `value`.3. Thread 2 changes the value of `value` from A to B and then back to A.4. Thread 1 performs a CAS operation to compare the current value of `value` with the expected value A and finds it to be equal, assuming that no changes have occurred.5. Thread 1 proceeds with its operations based on the assumption that the value is still A, unaware that an intermediate change from B to A has occurred.
getStamp metodu
Örnek
Şöyle yaparız
AtomicStampedReference<String> ref = new AtomicStampedReference<>("Initial", 0); System.out.println("Current Reference: " + ref.getReference()); System.out.println("Current Stamp: " + ref.getStamp()); // Set a new reference with a new stamp ref.set("Updated", 1); System.out.println("Updated Reference: " + ref.getReference()); System.out.println("Updated Stamp: " + ref.getStamp()); // Compare and set reference and stamp boolean success = ref.compareAndSet("Updated", "NewValue", 1, 2); System.out.println("Compare and Set Success: " + success); System.out.println("Updated Reference: " + ref.getReference()); System.out.println("Updated Stamp: " + ref.getStamp());
compareAndSet metodu
Örnek
Şöyle yaparız
static AtomicStampedReference<String> sharedVar = new AtomicStampedReference<>("A", 0);// Thread 1new Thread(() -> {int stamp = sharedVar.getStamp();String value = sharedVar.getReference();// Perform operations on value// Simulate an intermediate changesharedVa.compareAndSet(value, "B", stamp, stamp + 1);// Continue with operations// Change value back to AsharedVar.compareAndSet("B", "A", stamp + 1, stamp + 2);}).start();// Thread 2new Thread(() -> {int stamp = sharedVar.getStamp();String value = sharedVar.getReference();// Perform operations on value// Attempt to change value from A to Bboolean success = sharedVar.compareAndSet(value, "B", stamp, stamp + 1);if (success) {// Value changed successfully from A to B// ...// Change value back to AsharedVar.compareAndSet("B", "A", stamp + 1, stamp + 2);} else {// Intermediate change occurred. Handle the ABA problem}}).start();
Hiç yorum yok:
Yorum Gönder