在对象池中,你可能会面对一些共享对象的问题。你肯能需要创建一个方案包括共享对象的迁出或者迁入。
package design; import java.util.ArrayList; /** * Created by Administrator on 2018/4/18. */ public class PoolManager { private static class PoolItem{ boolean inUse=false; Object item; PoolItem(Object item){ this.item=item; } } private ArrayList items=new ArrayList(); public void add(Object item){ items.add(new PoolItem(item)); } static class EmptyPoolException extends Exception{} public Object get() throws EmptyPoolException{ for(int i=0;i<items.size();i++){ PoolItem poolItem=(PoolItem) items.get(i); if(poolItem.inUse==false) poolItem.inUse=true; return poolItem.item; } throw new EmptyPoolException(); } public void release(Object item){ for(int i=0;i<items.size();i++){ PoolItem poolItem=(PoolItem) items.get(i); if(item==poolItem.item){ poolItem.inUse=false; return; } } throw new RuntimeException(item+"not found"); } }
public interface Connection { Object get(); void set(Object x); }
public class ConnectionImplementation implements Connection { public Object get() { return null; } public void set(Object x) { } }
public class ConnectionPool { private static PoolManager poolManager=new PoolManager(); public static void addConnection(int number){ for(int i=0;i<number;i++) poolManager.add(new ConnectionImplementation()); } public static Connection getConnection() throws PoolManager.EmptyPoolException { return (Connection)poolManager.get(); } public static void releaseConnection(Connection c) { poolManager.release(c); } }
public class ConnectionPoolDemo extends TestCase { 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[]) { junit.textui.TestRunner.run(ConnectionPoolDemo.class); } }