/** * Gets the underlying buffer if its size is at most two times more than the actual data written * on the buffer. * * If this is not the case, creates a newly allocated byte array. Its size is the current size * of the actual content of this output stream and the valid contents of the buffer have been * copied into it. If the last 3 consecutive calls have resulted in new buffer creation, the * underlying buffer is replaced with the last created buffer while keeping the same count * position. */ public byte[] getCompactBuffer() { //If count is less then half of the capacity we return a compacted buffer if (_count <= getCapacity() >> 1) { byte newbuf[] = new byte[_count]; System.arraycopy(_buffer, 0, newbuf, 0, _count); if (++_compactionNeededTimes >= 3) { _compactionNeededTimes = 0; _buffer = newbuf; } return newbuf; } _compactionNeededTimes = 0; return _buffer; } }