首页

关于tomcat源码中基于Object数组定义SimplePool简单对象池的实现源码说明

标签:tomcat源码,pool池设计,SimplePool,简单对象池     发布时间:2018-10-24   

一、前言

关于tomcat源码中org.apache.tomcat.util.collections.SimplePool简单对象池实现,基于Object对象数组和标记属性(最大值标记max、当前存储标记current),详情参见源码说明部分。

二、源码说明

package org.apache.tomcat.util.collections;@b@@b@public final class SimplePool  {@b@    @b@    @b@    private static org.apache.juli.logging.Log log=@b@        org.apache.juli.logging.LogFactory.getLog(SimplePool.class );@b@    @b@    /*@b@     * Where the threads are held.@b@     */@b@    private Object pool[];@b@@b@    private int max;@b@    private int last;@b@    private int current=-1;@b@    @b@    private Object lock;@b@    public static final int DEFAULT_SIZE=32;@b@    static final int debug=0;@b@    @b@    public SimplePool() {@b@	this(DEFAULT_SIZE,DEFAULT_SIZE);@b@    }@b@@b@    public SimplePool(int size) {@b@	this(size, size);@b@    }@b@@b@    public SimplePool(int size, int max) {@b@	this.max=max;@b@	pool=new Object[size];@b@	this.last=size-1;@b@	lock=new Object();@b@    }@b@@b@    public  void set(Object o) {@b@	put(o);@b@    }@b@@b@    /**@b@     * Add the object to the pool, silent nothing if the pool is full@b@     */@b@    public  void put(Object o) {@b@	synchronized( lock ) {@b@	    if( current < last ) {@b@			current++;@b@			pool[current] = o;@b@        } else if( current < max ) {@b@			// realocate@b@			int newSize=pool.length*2;@b@			if( newSize > max ) newSize=max+1;@b@			Object tmp[]=new Object[newSize];@b@			last=newSize-1;@b@			System.arraycopy( pool, 0, tmp, 0, pool.length);@b@			pool=tmp;@b@			current++;@b@			pool[current] = o;@b@	    }@b@	    if( debug > 0 ) log("put " + o + " " + current + " " + max );@b@	}@b@    }@b@@b@    /**@b@     * Get an object from the pool, null if the pool is empty.@b@     */@b@    public  Object get() {@b@	Object item = null;@b@	synchronized( lock ) {@b@	    if( current >= 0 ) {@b@			item = pool[current];@b@			pool[current] = null;@b@			current -= 1;@b@	    }@b@	    if( debug > 0 ) @b@		log("get " + item + " " + current + " " + max);@b@	}@b@	return item;@b@    }@b@@b@    /**@b@     * Return the size of the pool@b@     */@b@    public int getMax() {@b@	return max;@b@    }@b@@b@    /**@b@     * Number of object in the pool@b@     */@b@    public int getCount() {@b@		return current+1;@b@    }@b@@b@@b@    public void shutdown() {@b@    }@b@    @b@    private void log( String s ) {@b@        if (log.isDebugEnabled())@b@            log.debug("SimplePool: " + s );@b@    }@b@}