同步栈(安全栈):

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;
}

举例:  

 

相关文章:

  • 2021-04-08
  • 2021-09-01
  • 2021-09-02
  • 2022-12-23
  • 2021-06-26
猜你喜欢
  • 2022-03-04
  • 2021-10-19
  • 2021-05-25
  • 2021-07-22
  • 2021-09-16
  • 2021-11-21
  • 2021-11-28
相关资源
相似解决方案