shz.core.queue.a.ConcurrentDArrayQueue Maven / Gradle / Ivy
package shz.core.queue.a;
import shz.core.constant.ArrayConstant;
/**
* 元素类型为double基于循环动态数组的队列
*
* 24+8*n(n为元素个数)=es
*
* B=56+8*n
*/
public class ConcurrentDArrayQueue extends ConcurrentArrayQueue {
protected double[] es;
protected ConcurrentDArrayQueue(int capacity) {
super(capacity);
es = new double[capacity];
}
public static ConcurrentDArrayQueue of(int capacity) {
return new ConcurrentDArrayQueue(capacity);
}
public static ConcurrentDArrayQueue of() {
return of(DEFAULT_CAPACITY);
}
@Override
protected final Double get(int i) {
return es[i];
}
@Override
protected final void resize(int capacity) {
double[] temp = new double[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] = 0d;
}
public final void offer(double e) {
writeLock.lock();
try {
beforeOffer();
es[tail] = e;
afterOffer();
} finally {
writeLock.unlock();
}
}
public final double poll() {
writeLock.lock();
try {
double e = es[head];
afterPoll();
return e;
} finally {
writeLock.unlock();
}
}
public final double head() {
readLock.lock();
try {
return es[head];
} finally {
readLock.unlock();
}
}
public final double tail() {
readLock.lock();
try {
return es[tail == 0 ? capacity - 1 : tail - 1];
} finally {
readLock.unlock();
}
}
public final double[] toArray() {
if (size == 0) return ArrayConstant.EMPTY_DOUBLE_ARRAY;
double[] array = new double[size];
int idx = 0;
int current = head;
while (current != tail) {
array[idx++] = es[current];
current = (current + 1) % capacity;
}
return array;
}
}