Note that there are some explanatory texts on larger screens.

plurals
  1. POWhere is there bug in lock free queue?
    primarykey
    data
    text
    <p>I wrote a Java lock free queue implementation. It has a concurrency bug. I cannot find it. This code is not important. I just worry about I cannot explain observed behavior related with volatile variables.</p> <p>The bug is visible by the exception ("null head"). This is impossible state because there is atomic integer holding current queue size. The queue has a stub element. It provides that a reader thread doesn't change tail pointer and a writer thread doesn't change head pointer.</p> <p>Queue length variable guarantee that the linked list will never be empty. It's as a semaphore.</p> <p>The take method behaves like it gets stolen length value.</p> <pre><code>class Node&lt;T&gt; { final AtomicReference&lt;Node&lt;T&gt;&gt; next = new AtomicReference&lt;Node&lt;T&gt;&gt;(); final T ref; Node(T ref) { this.ref = ref; } } public class LockFreeQueue&lt;T&gt; { private final AtomicInteger length = new AtomicInteger(1); private final Node stub = new Node(null); private final AtomicReference&lt;Node&lt;T&gt;&gt; head = new AtomicReference&lt;Node&lt;T&gt;&gt;(stub); private final AtomicReference&lt;Node&lt;T&gt;&gt; tail = new AtomicReference&lt;Node&lt;T&gt;&gt;(stub); public void add(T x) { addNode(new Node&lt;T&gt;(x)); length.incrementAndGet(); } public T takeOrNull() { while (true) { int l = length.get(); if (l == 1) { return null; } if (length.compareAndSet(l, l - 1)) { break; } } while (true) { Node&lt;T&gt; r = head.get(); if (r == null) { throw new IllegalStateException("null head"); } if (head.compareAndSet(r, r.next.get())) { if (r == stub) { stub.next.set(null); addNode(stub); } else { return r.ref; } } } } private void addNode(Node&lt;T&gt; n) { Node&lt;T&gt; t; while (true) { t = tail.get(); if (tail.compareAndSet(t, n)) { break; } } if (t.next.compareAndSet(null, n)) { return; } throw new IllegalStateException("bad tail next"); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload