解读spring.util包之FastByteArrayOutputStream

     org.springframework.util包中包含了不少很有趣的算法实现,比如 FastByteArrayOutputStream。doc上说,是一个比ByteArrayOutputStream更快的实现算法。为此,专门看了下write方法。

   FastByteArrayOutputStream 采用的内部数据结构是一个LinkedList<byte[]> buffers来保存具体的数据,用index保存当前的数据存储相对于byte[]的位置,它能够在write的时候进行自动扩容,扩容的算法是按照2的多少次方进行的。下面针对 public void write(int datum) throws IOException  具体说明。

	// The buffers used to store the content bytes 存储字节的数据结构,每一个byte[]是一个数据块
	private final LinkedList<byte[]> buffers = new LinkedList<byte[]>();

	// The size, in bytes, to use when allocating the first byte[]  初始的块容量
	private final int initialBlockSize;

	// The size, in bytes, to use when allocating the next byte[] 预备给下一个块(byte[])的容量
	private int nextBlockSize = 0;

	// The number of bytes in previous buffers.
	// (The number of bytes in the current buffer is in 'index'.)  所有的byte[]的总容量
	private int alreadyBufferedSize = 0;

	// The index in the byte[] found at buffers.getLast() to be written next  最后一个byte[]块的将要填充字节的index
	private int index = 0;

在initialBlockSize=0情况下

1  第1次 write(1)

  buffers 链表中,插入了第一个块,块的长度是1(2的0次方),这时候index回归为0,nextBlockSIze变为2(2的1次方),alreadyBufferedSize 变为0,

2 第2次 write(1)

     buffers 链表中,插入了第二个块,块的长度是2(2的1次方),这时候index变为1,nextBlockSIze变为4(2的2次方),alreadyBufferedSize 变为1

3  第3次 write(1)

    buffers 链表中,不插入块,这时候index回归0,nextBlockSIze和alreadyBufferedSize不变。

3  第4次 write(1)

    
     buffers 链表中,插入了第三个块,块的长度是4(2的2次方),这时候index变为1,nextBlockSIze变为8(2的3次方),alreadyBufferedSize 变为3


这就是基本扩容算法,细看下去并不复杂。



猜你喜欢

转载自blog.csdn.net/u014112608/article/details/76671348