package com.github.davidmoten.rx2;

import java.util.concurrent.atomic.AtomicReference;

import com.github.davidmoten.guavamini.Preconditions;

public class MpscQueue<T> {

    private final AtomicReference<Node<T>> head = new AtomicReference<Node<T>>();
    private Node<T> tail;

    private static class Node<T> {
        T value;
        Node<T> next;

        public Node(T value) {
            this.value = value;
        }
    }

    public void push(T value) {
        Preconditions.checkNotNull(value, "cannot push a null value");
        // CAS loop
        while (true) {
            Node<T> h = head.get();
            Node<T> node = new Node<T>(value);
            if (head.compareAndSet(h, node)) {
                h.next = node;
                if (tail == null) {
                    tail = h;
                }
                break;
            }
        }
    }

    public T poll() {
        if (tail == null) {
            return null;
        } else {
            Node<T> next = tail.next;
            T v = tail.value;
            // help gc including prevent nepotism
            tail.value = null;
            tail = next;
            return v;
        }
    }

}

@@ -244,24 +244,114 @@
 Node%3CT%3E%3E();%0A
+    private final AtomicReference%3CBoolean%3E tailSet = new AtomicReference%3CBoolean%3E(false);%0A
     private 
@@ -364,16 +364,16 @@
 %3E tail;%0A
-
 %0A    pri
@@ -643,16 +643,59 @@
 AS loop%0A
+        Node%3CT%3E node = new Node%3CT%3E(value);%0A
         
@@ -749,55 +749,8 @@
 ();%0A
-            Node%3CT%3E node = new Node%3CT%3E(value);%0A
     
@@ -843,32 +843,54 @@
     if (tail
- == null
+Set.compareAndSet(false, true)
 ) %7B%0A        
@@ -1075,16 +1075,53 @@
  else %7B%0A
+            Node%3CT%3E tempTail = tail;%0A
         
@@ -1136,24 +1136,28 @@
 %3CT%3E next = t
+empT
 ail.next;%0A  
@@ -1150,24 +1150,106 @@
 pTail.next;%0A
+            if (next == null) %7B%0A                tailSet.set(false);%0A            %7D%0A
             
@@ -1255,16 +1255,20 @@
  T v = t
+empT
 ail.valu
@@ -1320,16 +1320,16 @@
 epotism%0A
-
         
@@ -1333,16 +1333,20 @@
        t
+empT
 ail.valu

test dev