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

shz.core.queue.a.ConcurrentIArrayQueue 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 java.util.Objects;
import java.util.function.IntConsumer;

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

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

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