光辉飞翔

导航

 

同步栈(安全栈):

org.apache.tomcat.util.collections.SynchronizedStack
通过stack栈锁来控制栈中获取的类T。通过push、pop和clear方法操作栈对象。栈初始化大小是128,没有上限。

初始化:
public SynchronizedStack() {
this(DEFAULT_SIZE:128, DEFAULT_LIMIT:-1);
}

压入栈:
public synchronized boolean push(T obj) {
index++;
if (index == size) {
if (limit == -1 || size < limit) {
expand();
} else {
index--;
return false;
}
}
stack[index] = obj;
return true;
}

private void expand() {
int newSize = size * 2;
if (limit != -1 && newSize > limit) {
newSize = limit;
}
Object[] newStack = new Object[newSize];
System.arraycopy(stack, 0, newStack, 0, size);
// This is the only point where garbage is created by throwing away the
// old array. Note it is only the array, not the contents, that becomes
// garbage.
stack = newStack;
size = newSize;
}

获取栈对象:
public synchronized T pop() {
if (index == -1) {
return null;
}
T result = (T) stack[index];
stack[index--] = null;
return result;
}

清除栈释放资源:
public synchronized void clear() {
if (index > -1) {
for (int i = 0; i < index + 1; i++) {
stack[i] = null;
}
}
index = -1;
}

举例:  

 

posted on 2019-07-18 17:20  光辉飞翔  阅读(169)  评论(0编辑  收藏  举报