通过AtomicReference 实现 CAS 操作,完成无锁的SafeQueue
package com.john.learn.high.concurent.ch03.tools.support;
public class Node<T> {
public Node prev;
public Node next;
public T item;
}
package com.john.learn.high.concurent.ch03.tools.support;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class SafeQueue<T> {
private Node<T> head;
private AtomicReference<Node> atomicReferenceTail = null;
public SafeQueue() {
this.head = new Node();
atomicReferenceTail = new AtomicReference<Node>(this.head);
}
public void push(T item) {
Node<T> node = new Node<T>();
node.item = item;
for (;;) {
Node t = atomicReferenceTail.get();
node.prev = t;
// 线程安全
if (atomicReferenceTail.compareAndSet(t, node)) {
t.next = node;
return;
}
}
}
// poll
public T poll() {
for (;;) {
Node<T> tail = this.atomicReferenceTail.get();
Node<T> prev = tail.prev;
if (tail == this.head) {
if (atomicReferenceTail.compareAndSet(tail, this.head)) {
tail.prev = null;
}
return null;
}
if (atomicReferenceTail.compareAndSet(tail, prev)) {
tail.next = null;
return tail.item;
}
}
}
public Iterator<T> iterator() {
return new Iterator<T>() {
private Node<T> node = head;
public boolean hasNext() {
node = node.next;
return node != null;
}
public T next() {
return node.item;
}
};
}
}