In your example condition pointer.get() == null
always returns false
excepts first case when you assign it to head
, because in Node
class it null
. You can assign it with default value and remove null check.
I suggest you to change a bit Node class, make it immutable:
private static class Node<V> {
private final AtomicReference<Node> next = new AtomicReference<>();
private final V data;
private final String threadName;
Node(V data1, String threadName) {
this.data = data1;
this.threadName = threadName;
}
}
And then you can simple go through all elements:
private final AtomicReference<Node> head = new AtomicReference<>();
@SuppressWarnings("unchecked")
public void offer(final V data) {
// create new Node
final Node<V> newNode = new Node<>(data, Thread.currentThread().getName());
// set root element if it's null
if (head.compareAndSet(null, newNode)) {
return;
}
// else pass trough all elements and try to set new
Node<V> pointer = head.get();
for (;;) {
if (pointer.next.compareAndSet(null, newNode)) {
break;
}
pointer = pointer.next.get();
}
}
And change print method:
@SuppressWarnings("unchecked")
public void printQueueData() {
AtomicReference<Node> pointer = head;
while (pointer.get() != null) {
System.out.println(pointer.get().data);
pointer = pointer.get().next;
}
}