package org.rui.util;
import java.util.ArrayList;
/**
* 对象复用模式
*
* @author PC
*
*/
public class PoolManager
{
//连接池对象
public static class PoolItem
{
boolean inUse = false;
Object item;//池数据
PoolItem(Object item)
{
this.item = item;
}
}
//连接池集合
private ArrayList items = new ArrayList();
public void add(Object item)
{
this.items.add(new PoolItem(item));
}
static class EmptyPoolException extends Exception
{
}
public Object get() throws EmptyPoolException
{
for (int i = 0; i < items.size(); i++)
{
PoolItem pitem = (PoolItem) items.get(i);
if (pitem.inUse == false)
{
pitem.inUse = true;
return pitem.item;
}
}
throw new EmptyPoolException();
// return null;
}
/**
* 释放连接
* @param item
*/
public void release(Object item)
{
for (int i = 0; i < items.size(); i++)
{
PoolItem pitem = (PoolItem) items.get(i);
if (item == pitem.item)
{
pitem.inUse = false;
return;
}
}
throw new RuntimeException(item + " not null");
}
}
package org.rui.util;
import org.junit.Test;
/**
* 对象池(Object pool)
*
* 并没有限制说只能创建一个对象。这种技术同样适用于创建固定数量的对象,但
* 是,这种情况下,你就得面对如何共享对象池里的对象这种问题。如果共享对象很成
* 问题得话,你可以考虑以签入(check-in)签出(check-out)共享对象作为一种解决
* 方案。比如,就数据库来说,商业数据库通常会限制某一时刻可以使用的连接的个 数。下面这个例子就用对象池(object
* pool)实现了对这些数据库连接的管理。首 先,对象池对象(a pool of objects)的基本管理是作为一个单独的类来实现的。
*
* @author PC
*
*/
interface Connection
{
Object get();
void set(Object x);
}
class ConnectionImplementation implements Connection
{
public Object get()
{
return null;
}
public void set(Object s)
{
}
}
class ConnectionPool
{
//池管理对象
private static PoolManager pool = new PoolManager();
//指定连接数 并添加
public static void addConnections(int number)
{
for (int i = 0; i < number; i++)
pool.add(new ConnectionImplementation());
}
//获取连接
public static Connection getConnection()
throws PoolManager.EmptyPoolException
{
return (Connection) pool.get();
}
//释放指定的连接
public static void releaseConnection(Connection c)
{
pool.release(c);
}
}
//演示使用
public class ConnectionPoolDemo
{
static
{
ConnectionPool.addConnections(5);
}
@Test
public void test()
{
Connection c = null;
try
{
// 获得连接
c = ConnectionPool.getConnection();
} catch (PoolManager.EmptyPoolException e)
{
throw new RuntimeException(e);
}
// 设值
c.set(new Object());
//获取
c.get();
// 释放
ConnectionPool.releaseConnection(c);
}
@Test
public void test2()
{
Connection c = null;
try
{
c = ConnectionPool.getConnection();
} catch (PoolManager.EmptyPoolException e)
{
throw new RuntimeException(e);
}
c.set(new Object());
c.get();
ConnectionPool.releaseConnection(c);
}
public static void main(String args[])
{
// junit.textui.TestRunner.run(ConnectionPoolDemo.class);
}
}