All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.core.queue.a.ConcurrentZArrayQueue Maven / Gradle / Ivy

There is a newer version: 2024.0.2
Show newest version
package shz.core.queue.a;

import shz.core.constant.ArrayConstant;
import shz.core.function.BooleanConsumer;

import java.util.Objects;

/**
 * 元素类型为boolean基于循环动态数组的队列
 * 

* 24+n(n为元素个数)=es *

* B=56+n+对齐填充 */ public class ConcurrentZArrayQueue extends ConcurrentArrayQueue { private static final long serialVersionUID = -8577117644571537165L; protected boolean[] es; public ConcurrentZArrayQueue(int capacity) { super(capacity); es = new boolean[this.capacity]; } public ConcurrentZArrayQueue() { this(DEFAULT_CAPACITY); } public static ConcurrentZArrayQueue of(int capacity) { return new ConcurrentZArrayQueue(capacity); } public static ConcurrentZArrayQueue of() { return new ConcurrentZArrayQueue(); } @Override protected final void resize(int capacity) { boolean[] temp = new boolean[capacity]; for (int i = 0; i < size; ++i) temp[i] = es[(i + head) % this.capacity]; this.capacity = capacity; head = 0; tail = size; es = temp; } @Override protected final void setNull(int i) { es[i] = false; } public final void offer(boolean e) { writeLock.lock(); try { beforeOffer(); es[tail] = e; afterOffer(); } finally { writeLock.unlock(); } } public final boolean poll() { writeLock.lock(); try { checkEmpty(); boolean e = es[head]; afterPoll(); return e; } finally { writeLock.unlock(); } } public final boolean head() { readLock.lock(); try { checkEmpty(); return es[head]; } finally { readLock.unlock(); } } public final boolean tail() { readLock.lock(); try { checkEmpty(); return es[tail == 0 ? capacity - 1 : tail - 1]; } finally { readLock.unlock(); } } public final boolean get(int idx) { readLock.lock(); try { if (idx < 0 || idx >= size) throw new IndexOutOfBoundsException(); return es[(head + idx) % capacity]; } finally { readLock.unlock(); } } public final boolean[] toArray() { readLock.lock(); try { if (size == 0) return ArrayConstant.EMPTY_BOOLEAN_ARRAY; boolean[] array = new boolean[size]; int idx = 0; int current = head; while (current != tail) { array[idx++] = es[current]; current = (current + 1) % capacity; } return array; } finally { readLock.unlock(); } } public final void forEach(BooleanConsumer action) { Objects.requireNonNull(action); readLock.lock(); try { int current = head; while (current != tail) { action.accept(es[current]); current = (current + 1) % capacity; } } finally { readLock.unlock(); } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy