public class MyURLConnectionPoolableObjectFactory implements PoolableObjectFactory<MyURLConnection> { AtomicInteger ato = new AtomicInteger(0); @Override public MyURLConnection makeObject() throws Exception { MyURLConnection connection = new MyURLConnection("connection"+ato.incrementAndGet()); connection.setConnected(true); System.out.println(connection.getName()+",makeObject"); return connection; } @Override public void destroyObject(MyURLConnection connection) throws Exception { connection.setClose(true); System.out.println(connection.getName()+",destroyObject"); } @Override public boolean validateObject(MyURLConnection connection) { System.out.println(connection.getName()+",validateObject"); return !connection.isClose(); } @Override public void activateObject(MyURLConnection connection) throws Exception { System.out.println(connection.getName()+",activateObject"); } @Override public void passivateObject(MyURLConnection connection) throws Exception { System.out.println(connection.getName()+",passivateObject"); } }
public class MyURLConnectionTest { public static void main(String[] args) throws Exception { PoolableObjectFactory factory = new MyURLConnectionPoolableObjectFactory(); ObjectPool pool = new StackObjectPool(factory); try { System.out.println("===================First Phase============================="); for (int i = 0; i < 10; i++) { MyURLConnection connection = (MyURLConnection)pool.borrowObject(); boolean exception = false; try { if(i==4){ throw new Exception("not ok."); } connection.send(); } catch(Exception ex) { ex.printStackTrace(); pool.invalidateObject(connection); //会调用destroyObject System.out.println("============================================================"); exception = true; } finally { if(!exception){ pool.returnObject(connection); } } } System.out.println("===================Second Phase ============================="); for (int i = 0; i < 10; i++) { MyURLConnection connection1 = (MyURLConnection)pool.borrowObject(); MyURLConnection connection2 = (MyURLConnection)pool.borrowObject(); connection1.send(); connection2.send(); pool.returnObject(connection1); pool.returnObject(connection2); } } finally { try { pool.close(); } catch (Exception e) { e.printStackTrace(); } } } }