商业数据库通常会限制某一时刻可以使用的连接的个数。下面这个例子就用对象池(Object pool)实现了对这些数据库连接的管理。首先,对象池对象的基本管理是作为一个单独的类来实现。
PoolManager .java
package com.enfo.wd.patterns;
import java.util.ArrayList;
public class PoolManager {
private static class PoolItem{
boolean inUse=false;
Object item;
PoolItem(Object item){
this.item=item;
}
}
@SuppressWarnings("rawtypes")
private ArrayList items=new ArrayList();
@SuppressWarnings("unchecked")
void add(Object item){
items.add(new PoolItem(item));
}
@SuppressWarnings("serial")
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();
}
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 found");
}
}
ConnectionPoolDemo .java
package com.enfo.wd.patterns;
interface Connection{
Object get();
void set(Object x);
}
class ConnectionImplementation implements Connection{
@Override
public Object get() {
return null;
}
@Override
public void set(Object x) {
}
}
class ConnectionPool{
private static PoolManager pool=new PoolManager();
public static void addConnection(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.addConnection(5);
}
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);
}
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) {
ConnectionPoolDemo e=new ConnectionPoolDemo();
e.test();
e.test2();
}
}