1、Connection接口
1 package com.xinye.test.pool3; 2 3 public interface Connection { 4 void set(Object obj); 5 void get(); 6 }
2、Connection实现
1 package com.xinye.test.pool3; 2 3 public class ConnectionImpl implements Connection { 4 5 @Override 6 public void set(Object obj) { 7 8 } 9 10 @Override 11 public void get() { 12 13 } 14 15 }
3、Connection代理类
1 package com.xinye.test.pool3; 2 /** 3 * 4 * @author xinye 5 * 6 */ 7 public class ConnectionProxy implements Connection{ 8 private ReleaseablePoolItem<Connection> releaseable = null; 9 public ConnectionProxy(ReleaseablePoolItem<Connection> rel){ 10 this.releaseable = rel; 11 } 12 @Override 13 public void set(Object obj) { 14 releaseable.getReference().set(obj); 15 } 16 17 @Override 18 public void get() { 19 releaseable.getReference().get(); 20 } 21 22 }
4、连接池
1 package com.xinye.test.pool3; 2 3 public class ConnectionPool { 4 private static PoolManager<Connection> manager = new PoolManager<Connection>(); 5 private ConnectionPool(){ 6 7 } 8 public static void add(int num){ 9 for(int i = 0;i < num;i++){ 10 manager.add(new ConnectionImpl()); 11 } 12 } 13 public static Connection getConnection(){ 14 ReleaseablePoolItem<Connection> conn = manager.get(); 15 if(conn == null){ 16 return null; 17 } 18 return new ConnectionProxy(conn); 19 } 20 21 }
5、池子中放的东西
1 package com.xinye.test.pool3; 2 3 public class PoolItem <T>{ 4 public boolean isUse = false; 5 public T item; 6 public PoolItem(T t){ 7 this.item = t; 8 } 9 }
6、释放对象的时候不能再使用
1 package com.xinye.test.pool3; 2 /** 3 * 4 * @author 5 * 6 * @param <T> 7 */ 8 public class ReleaseablePoolItem <T>{ 9 public PoolItem<T> reference; 10 public boolean released = false; 11 public ReleaseablePoolItem(PoolItem<T> reference){ 12 13 this.reference = reference; 14 15 } 16 public T getReference(){ 17 if(released){ 18 throw new RuntimeException("Tried to use reference after it was released"); 19 } 20 return reference.item; 21 } 22 public void release(){ 23 released = true; 24 reference.isUse = false; 25 } 26 }
7、池子管理对象
1 package com.xinye.test.pool3; 2 3 import java.util.ArrayList; 4 5 public class PoolManager <T> { 6 private ArrayList<PoolItem<T>> list = new ArrayList<PoolItem<T>>(); 7 8 public void add(T t){ 9 list.add(new PoolItem<T>(t)); 10 } 11 public ReleaseablePoolItem<T> get(){ 12 int len = list.size(); 13 for(int i = 0;i < len;i++){ 14 PoolItem<T> item = list.get(i); 15 if(item.isUse == false){ 16 item.isUse = true; 17 return new ReleaseablePoolItem<T>(item); 18 } 19 } 20 return null; 21 } 22 }