1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| /** * 继承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)); } @Override public void close() throws IOException { //当输出流关闭的时候,释放该byte[]回到byte缓冲池中 mPool.returnBuf(buf); buf = null; super.close(); } @Override public 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) * 2 byte[] 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)中 */ @Override public synchronized void write(byte[] buffer, int offset, int len) { expand(len); super.write(buffer, offset, len); } @Override public synchronized void write(int oneByte) { //扩展1个字节长度 expand(1); super.write(oneByte); } }
|