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

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

package shz.core.queue.a;

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

import java.util.Objects;

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

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

* B=56+n+对齐填充 */ public class ConcurrentBArrayQueue extends ConcurrentArrayQueue { private static final long serialVersionUID = -7249495336450321774L; protected byte[] es; public ConcurrentBArrayQueue(int capacity) { super(capacity); es = new byte[capacity]; } public ConcurrentBArrayQueue() { this(DEFAULT_CAPACITY); } public static ConcurrentBArrayQueue of(int capacity) { return new ConcurrentBArrayQueue(capacity); } public static ConcurrentBArrayQueue of() { return new ConcurrentBArrayQueue(); } @Override protected final void resize(int capacity) { byte[] temp = new byte[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] = 0; } public final void offer(byte e) { writeLock.lock(); try { beforeOffer(); es[tail] = e; afterOffer(); } finally { writeLock.unlock(); } } public final byte poll() { writeLock.lock(); try { checkEmpty(); byte e = es[head]; afterPoll(); return e; } finally { writeLock.unlock(); } } public final byte head() { readLock.lock(); try { checkEmpty(); return es[head]; } finally { readLock.unlock(); } } public final byte tail() { readLock.lock(); try { checkEmpty(); return es[tail == 0 ? capacity - 1 : tail - 1]; } finally { readLock.unlock(); } } public final byte get(int idx) { readLock.lock(); try { if (idx < 0 || idx >= size) throw new IndexOutOfBoundsException(); return es[(head + idx) % capacity]; } finally { readLock.unlock(); } } public final byte[] toArray() { readLock.lock(); try { if (size == 0) return ArrayConstant.EMPTY_BYTE_ARRAY; byte[] array = new byte[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(ByteConsumer 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 - 2025 Weber Informatics LLC | Privacy Policy