Skip to content

Commit

Permalink
Merge pull request #434 from kmgowda/kmg-cq-1
Browse files Browse the repository at this point in the history
Atomic queue and CQueue performance optimisations

Signed-off-by: Keshava Munegowda <keshava.gowda@gmail.com>
  • Loading branch information
kmgowda authored May 31, 2024
2 parents 1d9aa61 + 46587eb commit 5f9e836
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
23 changes: 21 additions & 2 deletions perl/src/main/java/io/perl/api/impl/AtomicQueue.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ public AtomicQueue() {
this.tail = new AtomicReference<>(firstNode);
}

@Override
public T poll() {
public T pollOnce() {
final Node<T> curHead = head.getAndSet(null);
if (curHead == null) {
return null;
Expand All @@ -56,6 +55,25 @@ public T poll() {
return nxt.item;
}

@Override
public T poll() {
Node<T> curHead = head.get();
Node<T> nxt = curHead.next.get();

while ( nxt != null && !head.compareAndSet(curHead, nxt) ) {
curHead = head.get();
nxt = curHead.next.get();
}

if (nxt == null) {
return null;
}
curHead.next.set(null);

return nxt.item;
}


@Override
public boolean add(T data) {
final Node<T> node = new Node<>(data);
Expand All @@ -66,6 +84,7 @@ public boolean add(T data) {

@Override
public void clear() {
firstNode.next.set(null);
Node<T> first = head.getAndSet(firstNode);
tail.set(first);
/*
Expand Down
21 changes: 19 additions & 2 deletions perl/src/main/java/io/perl/api/impl/CQueue.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ public CQueue() {
this.tail = firstNode;
}

@Override
public T poll() {
public T pollOnce() {
final Object cur = NEXT.getAndSet(head, null);
if (cur == null) {
return null;
Expand All @@ -68,6 +67,23 @@ public T poll() {
return (T) ITEM.getAndSet(cur, null);
}

@Override
public T poll() {
Object curHead = HEAD.get(this);
Object nxt = NEXT.get(curHead);

while (nxt != null && !HEAD.compareAndSet(this, curHead, nxt)) {
curHead = HEAD.get(this);
nxt = NEXT.get(curHead);
}

if (nxt == null) {
return null;
}
NEXT.set(curHead, null);
return (T) ITEM.getAndSet(nxt, null);
}

@Override
public boolean add(T data) {
final Node<T> node = new Node<>(data);
Expand All @@ -78,6 +94,7 @@ public boolean add(T data) {

@Override
public void clear() {
NEXT.set(firstNode, null);
Object first = HEAD.getAndSet(this, firstNode);
TAIL.set(this, firstNode);
/*
Expand Down

0 comments on commit 5f9e836

Please sign in to comment.