8 Kasım 2023 Çarşamba

AtomicReference İle Stack Gerçekleştirimi

Örnek
Şöyle yaparız. Burada bir Stack gerçekleştirimi var ve head ve next değerleri atanıyor
public class MyConcurrentStack<T> {

  private AtomicReference<Node> head = new AtomicReference<Node>();

  public void push(T t) {
    if (t == null) {
      return;
    }
    Node<T> n = new Node<T>(t);
    Node<T> current;

    do {
      current = head.get();
      n.setNext(current);
    } while (!head.compareAndSet(current, n));
  }

  public T pop() {
    Node<T> currentHead = null;
    Node<T> futureHead = null;
    do {
      currentHead = head.get();
      if (currentHead == null) {
        return null;
      }
      futureHead = currentHead.next;
    } while (!head.compareAndSet(currentHead, futureHead));

    return currentHead.data;
  }
  
}
Örnek
Elimizde şöyle bir kod olsun
public class StackNode<T> {
  T data;
  StackNode next;

  public StackNode(T t) {
    data = t;
    next = null;
  }
}
Şöyle yaparız
public class AtomicStack<T> {
  private final AtomicReference<StackNode<T>> head = new AtomicReference<>();
private final AtomicInteger count = new AtomicInteger(0);
public int getCount() { return count.get(); } public T pop() { StackNode<T> currentStackHead; StackNode<T> newStackHead; while(true) { currentStackHead = head.get(); if(currentStackHead == null){ break; } newStackHead = currentStackHead.next; if(head.compareAndSet(currentStackHead, newStackHead)) { break; } else { LockSupport.parkNanos(1); } } count.decrementAndGet(); return currentStackHead != null ? currentStackHead.data: null; } public void push(T obj) { StackNode<T> newStackNode = new StackNode<>(obj); while (true) { StackNode<T> currentHead = head.get(); newStackNode.next = currentHead; if (head.compareAndSet(currentHead, newStackNode)) { break; } else { LockSupport.parkNanos(1); } } count.incrementAndGet(); } }


Hiç yorum yok:

Yorum Gönder