@946898963
2018-05-18T03:53:36.000000Z
字数 2475
阅读 1307
Android控件跟框架 Android源码分析
PoolingByteArrayOutputStream其实就是一个输出流,只不过系统的输出流在使用byte[]时,如果大小不够,会自动扩大byte[]的大小。而PoolingByteArrayOutputStream则是使用了ByteArrayPool的字节数组缓冲池,从池中获取byte[] 使用完毕后再归还。在BasicNetwork中对响应进行解析的时候使用到了该输出流。
源码分析,在注释中:
/*** 继承ByteArrayOutputStream,原始 ByteArrayOutputStream 中用于接受写入 bytes 的 buf,每次空间不足时便会 new 更大容量的 byte[],而 PoolingByteArrayOutputStream 使用了 ByteArrayPool 作为 Byte[] 缓存来减少这种操作,从而提高性能。** A variation of {@link java.io.ByteArrayOutputStream} that uses a pool of byte[] buffers instead* of always allocating them fresh, saving on heap churn.*/public class PoolingByteArrayOutputStream extends ByteArrayOutputStream {/*** 默认byte[]的大小** If the {@link #PoolingByteArrayOutputStream(ByteArrayPool)} constructor is called, this is* the default size to which the underlying byte array is initialized.*/private static final int DEFAULT_SIZE = 256;/*** byte[]的缓冲池*/private final ByteArrayPool mPool;/*** 带byte[]缓冲池的输出流,使用默认的byte[]长度* Constructs a new PoolingByteArrayOutputStream with a default size. If more bytes are written* to this instance, the underlying byte array will expand.*/public PoolingByteArrayOutputStream(ByteArrayPool pool) {this(pool, DEFAULT_SIZE);}/*** Constructs a new {@code ByteArrayOutputStream} with a default size of {@code size} bytes. If* more than {@code size} bytes are written to this instance, the underlying byte array will* expand.** @param size initial size for the underlying byte array. The value will be pinned to a default* minimum size.*/public PoolingByteArrayOutputStream(ByteArrayPool pool, int size) {mPool = pool;/*** buf,该输出流将要内容写入的目标byte[],如果多次写入,buf长度不够的时候需要扩展长度*/buf = mPool.getBuf(Math.max(size, DEFAULT_SIZE));}@Overridepublic void close() throws IOException {//当输出流关闭的时候,释放该byte[]回到byte缓冲池中mPool.returnBuf(buf);buf = null;super.close();}@Overridepublic void finalize() {//当垃圾回收机制准备回收该输出流时,将该byte[]回收到缓冲池mPool.returnBuf(buf);}/*** Ensures there is enough space in the buffer for the given number of additional bytes.* 扩充当前输出流正在使用的byte[]的大小*/private void expand(int i) {/* Can the buffer handle @i more bytes, if not expand it */if (count + i <= buf.length) {//当已经写入的字节数加上预计扩展的字节数之和,仍然不大于当前的byte[]的长度时,不需要扩展return;}//当当前的byte[]不再满足时,需要从byte[]缓冲池中获取一个byte[],大小为(count + i) * 2byte[] newbuf = mPool.getBuf((count + i) * 2);//将当前的byte[]内容复制到新的byte[]中System.arraycopy(buf, 0, newbuf, 0, count);//将旧的byte[]进行回收到byte[]缓冲池中mPool.returnBuf(buf);buf = newbuf;}/*** 从buffer的offset位置读len长度的内容,写入到输出流的byte[](buf)中*/@Overridepublic synchronized void write(byte[] buffer, int offset, int len) {expand(len);super.write(buffer, offset, len);}@Overridepublic synchronized void write(int oneByte) {//扩展1个字节长度expand(1);super.write(oneByte);}}