![JAR search and dependency download from the Maven repository](/logo.png)
shz.core.queue.l.ConcurrentLLinkedQueue Maven / Gradle / Ivy
package shz.core.queue.l;
import shz.core.constant.ArrayConstant;
import shz.core.node.LSNode;
import java.util.Objects;
import java.util.function.Consumer;
/**
* 元素类型为E基于链表的队列
*
* 20+16*(n+1)+(E+对齐填充)*n(n为元素个数)
*
* B=8+16*(n+3)+(E+对齐填充)*n
*/
@SuppressWarnings("unchecked")
public class ConcurrentLLinkedQueue extends ConcurrentLinkedQueue> {
private static final long serialVersionUID = 1911339705860858519L;
public static ConcurrentLLinkedQueue of() {
return new ConcurrentLLinkedQueue<>();
}
public final void offer(E e) {
writeLock.lock();
try {
LSNode temp = tail;
tail = LSNode.of(e);
if (head == null) head = tail;
else temp.next(tail);
++size;
} finally {
writeLock.unlock();
}
}
public final E poll() {
writeLock.lock();
try {
checkEmpty();
E val = head.val;
head = head.next();
if (head == null) tail = null;
--size;
return val;
} finally {
writeLock.unlock();
}
}
public final E head() {
readLock.lock();
try {
checkEmpty();
return head.val;
} finally {
readLock.unlock();
}
}
public final E tail() {
readLock.lock();
try {
checkEmpty();
return tail.val;
} finally {
readLock.unlock();
}
}
public final E[] toArray() {
readLock.lock();
try {
if (size == 0) return (E[]) ArrayConstant.EMPTY_OBJECT_ARRAY;
E[] array = (E[]) new Object[size];
int idx = 0;
LSNode current = head;
while (current != null) {
array[idx++] = current.val;
current = current.next();
}
return array;
} finally {
readLock.unlock();
}
}
public final void forEach(Consumer super E> action) {
Objects.requireNonNull(action);
readLock.lock();
try {
if (head != null) head.forEach((Consumer>) node -> action.accept(node.val));
} finally {
readLock.unlock();
}
}
}