基礎(chǔ)類僅提供了最基本的兩個(gè)函數(shù),用來創(chuàng)建和返回pool對(duì)象。 2.實(shí)現(xiàn)的基本類 BaSEObjectPool--PoolableObjectFactory--BasePoolableObjectFactory KeyedObjectPool--KeyedPoolableObjectFactory--BaseKeyedPoolableObjectFactory StackObjectPool--StackKeyedObjectPool--可以在初始化創(chuàng)建實(shí)例,提供有限的 idle 數(shù)量 GenericObjectPool--GenericKeyedObjectPool--包含了設(shè)定 idle, active 的數(shù)量以及回收到pool中的設(shè)置 SoftReferenceObjectPool--可以隨需要進(jìn)行增加,他的回收是由垃圾回收站進(jìn)行的 總的來說,它提供了 Pool 的 API 主要有三個(gè)方面: 提供一般性的對(duì)象 pool 接口, 可以簡(jiǎn)單地去使用和實(shí)現(xiàn). 比如BaseObjectPool和KeyedObjectPool. 提供小工具可以建立模塊化的 pool. 比如StackObjectPool. 實(shí)現(xiàn)出一些通用性的 pool. 比如GenericObjectPool. 3.實(shí)現(xiàn)
/** * Dumps the contents of the {@link Reader} to a * String, closing the {@link Reader} when done. */ public String readToString(Reader in) throws IOException { StringBuffer buf = new StringBuffer(); try {
for( int c = in.read(); c != -1; c = in.read()) { buf.append((char)c); } return buf.toString(); } catch(IOException e) { throw e; } finally { try { in.close(); } catch (Exception e) { // ignored } } } }
public class StringBufferFactory extends BasePoolableObjectFactory { // for makeObject we′ll simply return a new buffer public Object makeObject() { return new StringBuffer(); }
// when an object is returned to the pool, // we′ll clear it out public void passivateObject(Object obj) { StringBuffer buf = (StringBuffer)obj; buf.setLength(0); }
// for all other methods, the no-op // implementation in BasePoolableObjectFactory // will suffice }
修改 ReaderUtil 由 StringBufferFactory Pool 得到 StringBuffer.
new ReaderUtil( new StackObjectPool( new StringBufferFactory() ) ) 5.總結(jié) 我們通常會(huì)在 io 的部分采用 pool 機(jī)制, 減少一些建立存取的時(shí)間, 對(duì)于最耗時(shí)的數(shù)據(jù)庫存取, 更是相對(duì)的重要,我將會(huì)在commons-DBCP專題進(jìn)行介紹,本篇是本系列的第二篇,以后將陸續(xù)推出,下期主題就是DBCP,請(qǐng)繼續(xù)關(guān)注. 6.參考 -- 相關(guān)書目或相關(guān)文章 *Jakarta Commons: http://jakarta.apache.org/commons/ *Jakarta Commons Pool http://jakarta.apache.org/commons/pool/ *Jakarta Commons Pool API: http://jakarta.apache.org/commons/pool/apidocs/index.Html *Oreilly: Using the Jakarta Commons, Part 3: #3 http://www.onjava.com/pub/a/onjava/2003/07/23/commons.html?page=3