Note that there are some explanatory texts on larger screens.

plurals
  1. POIs this (Lock-Free) Queue Implementation Thread-Safe?
    primarykey
    data
    text
    <p>I am trying to create a lock-free queue implementation in Java, mainly for personal learning. The queue should be a general one, allowing any number of readers and/or writers concurrently.</p> <p>Would you please review it, and suggest any improvements/issues you find?</p> <p>Thank you.</p> <pre><code>import java.util.concurrent.atomic.AtomicReference; public class LockFreeQueue&lt;T&gt; { private static class Node&lt;E&gt; { E value; volatile Node&lt;E&gt; next; Node(E value) { this.value = value; } } private AtomicReference&lt;Node&lt;T&gt;&gt; head, tail; public LockFreeQueue() { // have both head and tail point to a dummy node Node&lt;T&gt; dummyNode = new Node&lt;T&gt;(null); head = new AtomicReference&lt;Node&lt;T&gt;&gt;(dummyNode); tail = new AtomicReference&lt;Node&lt;T&gt;&gt;(dummyNode); } /** * Puts an object at the end of the queue. */ public void putObject(T value) { Node&lt;T&gt; newNode = new Node&lt;T&gt;(value); Node&lt;T&gt; prevTailNode = tail.getAndSet(newNode); prevTailNode.next = newNode; } /** * Gets an object from the beginning of the queue. The object is removed * from the queue. If there are no objects in the queue, returns null. */ public T getObject() { Node&lt;T&gt; headNode, valueNode; // move head node to the next node using atomic semantics // as long as next node is not null do { headNode = head.get(); valueNode = headNode.next; // try until the whole loop executes pseudo-atomically // (i.e. unaffected by modifications done by other threads) } while (valueNode != null &amp;&amp; !head.compareAndSet(headNode, valueNode)); T value = (valueNode != null ? valueNode.value : null); // release the value pointed to by head, keeping the head node dummy if (valueNode != null) valueNode.value = null; return value; } </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.
 

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