zoukankan      html  css  js  c++  java
  • SynchronizedStack -- tomcat8同步栈

    同步栈(安全栈):

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

    举例:  
  • 相关阅读:
    单例模式
    建造者模式
    工厂模式
    八大排序算法之插入排序
    八大排序算法之基数排序
    lua 4 使用table实现其他数据结构,并介绍遍历方法
    lua 3 循环
    lua 2 变量
    lua 1 基本语法和注意事项
    template指针小测试
  • 原文地址:https://www.cnblogs.com/guanghuiqq/p/11209699.html
Copyright © 2011-2022 走看看