緩存池的作用就是減少重復(fù)創(chuàng)建資源,不是到每次需要使用資源再創(chuàng)建,而是提前準備好資源,每次需要時,從池中獲取,用完歸還.
我們看看下面簡單的 Hello World
從流中讀取字符串,每次都需要創(chuàng)建StringBuffer
import java.io.Reader;
import java.io.IOException;
public class ReaderUtil {
public ReaderUtil() {
}
/**
* 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
}
}
}
}
有些麻煩吧,我們使用緩存池獲取StringBuffer試試,直接上代碼
import java.io.IOException;
import java.io.Reader;
import org.apache.commons.pool2.ObjectPool;
public class ReaderUtil {
private ObjectPool<StringBuffer> pool;
public ReaderUtil(ObjectPool<StringBuffer> pool) {
this.pool = pool;
}
/**
* 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 = null;
try {
//通過緩存池獲取
buf = pool.borrowObject();
for (int c = in.read(); c != -1; c = in.read()) {
buf.append((char) c);
}
return buf.toString();
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Unable to borrow buffer from pool" + e.toString());
} finally {
try {
in.close();
} catch (Exception e) {
// ignored
}
try {
if (null != buf) {
//使用完歸還回緩存池
pool.returnObject(buf);
}
} catch (Exception e) {
// ignored
}
}
}
}
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
public class StringBufferFactory
extends BasePooledObjectFactory<StringBuffer> {
//創(chuàng)建對象的方法
@Override
public StringBuffer create() {
return new StringBuffer();
}
/**
* Use the default PooledObject implementation.
* 使用默認的池化對象DefaultPooledObject封裝StringBuffer,使之帶上狀態(tài)屬性
*/
@Override
public PooledObject<StringBuffer> wrap(StringBuffer buffer) {
return new DefaultPooledObject<StringBuffer>(buffer);
}
/**
* When an object is returned to the pool, clear the buffer.
* 鈍化對象,下次之前可以再復(fù)用該對象
*/
@Override
public void passivateObject(PooledObject<StringBuffer> pooledObject) {
pooledObject.getObject().setLength(0);
}
// for all other methods, the no-op implementation
// in BasePooledObjectFactory will suffice
}
ReaderUtil readerUtil = new ReaderUtil(new GenericObjectPool<StringBuffer>(new StringBufferFactory()));
代碼很簡單,下回代碼源碼解讀.