private void flushBuffers() throws IOException { checkNotClosed(); if (this.count > 0) { final ByteBuffer buffer = ByteBuffer.wrap(this.buffer); buffer.limit(this.count); this.buffers.add(buffer); } this.emitter.emit(this.buffers); if (!this.buffers.isEmpty()) { this.buffer = this.buffers.get(0).array(); this.buffers.clear(); } this.count = 0; this.threshold = BUFFER_SIZE; }
@Override public void close() throws IOException { synchronized (this.buffers) { if (this.closed) { return; } flushBuffers(); this.closed = true; } this.buffers.clear(); this.buffer = null; this.emitter.close(); this.emitter = null; }
@Override public void write(final byte[] buf, int off, int len) throws IOException { final int available = this.threshold - this.count; if (available >= len) { System.arraycopy(buf, off, this.buffer, this.count, len); this.count += len; return; } if (available > 0) { System.arraycopy(buf, off, this.buffer, this.count, available); this.count += available; off += available; len -= available; } final int end = off + len; while (off < end) { writeAndTryFlush(buf[off++]); } }
public static OutputStream parallelBuffer(final OutputStream stream, final byte delimiter) { return new ParallelBufferedOutputStream(stream, delimiter); }
@Override public void flush() throws IOException { flushBuffers(); }
@Override public void write(final int c) throws IOException { if (this.count < this.threshold) { this.buffer[this.count++] = (byte) c; } else { writeAndTryFlush((byte) c); } }
private void writeAndTryFlush(final byte c) throws IOException { this.buffer[this.count++] = c; if (c == this.delimiter) { flushBuffers(); } else if (this.count == this.buffer.length) { checkNotClosed(); this.buffers.add(ByteBuffer.wrap(this.buffer)); this.buffer = new byte[BUFFER_SIZE]; this.count = 0; this.threshold = 0; } }