pool.java

来自「一个简单的visio程序。」· Java 代码 · 共 104 行

JAVA
104
字号

package servlet.util;


public class Pool
{

    public Pool(String s, int i)
        throws IllegalArgumentException
    {
        if(i <= 0)
            throw new IllegalArgumentException("invalid count");
        count = i;
        try
        {
            init(Class.forName(s));
            return;
        }
        catch(ClassNotFoundException ex)
        {
            throw new IllegalArgumentException("class not found");
        }
    }

    public Pool(String s)
        throws IllegalArgumentException
    {
        this(s, 1);
    }

    public Pool(Class class1, int i)
        throws IllegalArgumentException
    {
        count = i;
        init(class1);
    }

    public Pool(Class class1)
        throws IllegalArgumentException
    {
        this(class1, 1);
    }

    protected void init(Class class1)
        throws IllegalArgumentException
    {
        free = new Object[count];
        try
        {
            for(int i = 0; i < count; i++)
                free[i] = class1.newInstance();

        }
        catch(InstantiationException ex)
        {
            throw new IllegalArgumentException("class could not be instantiated");
        }
        catch(IllegalAccessException ex)
        {
            throw new IllegalArgumentException("class not accessible");
        }
        cl = class1;
    }

    public Object alloc()
    {
        synchronized(this) 
        {
            if(count > 0)
            {
                Object obj = free[--count];
                return obj;
            }
        }
        try
        {
            return cl.newInstance();
        }
        catch(InstantiationException ex)
        {
            throw new InternalError();
        }
        catch(IllegalAccessException ex)
        {
            throw new InternalError();
        }
    }

    public synchronized void free(Object obj)
    {
        if(count >= free.length)
        {
            Object aobj[] = new Object[free.length * 2];
            System.arraycopy(free, 0, aobj, 0, free.length);
            free = aobj;
        }
        free[count++] = obj;
    }

    protected Class cl;
    protected Object free[];
    protected int count;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?