Yes, in Java, given that it has garbage collection, these ifs have only real value as optimization, and it's kind of big: CAS is incredibly expensive compared to just reading from memory, so make sure that the value hasnβt changed in the meantime, and thus reduces the likelihood of a failure on subsequent CASs, helps reduce the number of CAS attempts, which helps performance.
You can also transfer the first == last && tail update check inside head.CAS, as an additional optimization: the tail can lag only if the head has been updated, so checking that only if the CAS succeeds makes sense. You can also move tail.get there, since you no longer need it. Sample code below. Hope this helps!
public T deq() throws EmptyException { while(true) { Node first = head.get(); Node next = first.next.get(); if (first != head.get()) continue; if (next == null) { throw new EmptyException(); } T value = next.value; if (head.compareAndSet(first, next)) { Node last = tail.get(); if (first == last) { tail.compareAndSet(last, next); } return value; } }
}
llongi
source share