Interface BufferedEncodedOutput

All Superinterfaces:
AutoCloseable, Output<RuntimeException>, Output.CloseableEncodedOutput<RuntimeException>, Output.EncodedOutput<RuntimeException>
All Known Subinterfaces:
ByteBufferEncodedOutput, ChunkEncodedOutput<T>
All Known Implementing Classes:
ByteBufferedOutputStream

An encoded output that will store the output in its preferred memory structure and can then be copied to an OutputStream or read from a ReadableByteChannel. The total size() of the output can also be retrieved before being copied which is useful for setting "Content-Length" HTTP header or for allocating buffers.

The major impetus for this interface is needing the length of the output prior to outputing. If the length is not needed before writing then better performance and memory savings can probably be had by just using Output.EncodedOutput.of(OutputStream, Charset).

In general instances will be empty and not have correct results till Template.EncodedTemplate.write(Object, EncodedOutput) is called.

Currently there are two approaches to buffered output:

  • ByteBufferEncodedOutput: according to benchmarks on most platforms other than Windows it is more CPU friendly but less memory friendly. It is ideal for platforms where you can return ByteBuffer directly or need to return a byte[]. The default implementation uses a growing array and can be created with ByteBufferEncodedOutput.ofByteArray(Charset, int) and can be reused provided close() is called. Reuse can be useful if using ThreadLocals or some other pooling mechanism.
  • ChunkEncodedOutput: according to benchmarks is more optimized for memory savings as well as possible reduction of copying. This approach originated from Rocker's purported "near zero copy".
Regardless one should benchmark each approach to determine which one best fits for their platform. In many cases a custom Output.EncodedOutput that uses the platform's underlying buffer pool will probably yield the best results.
Author:
agentgt
See Also:
API Note
Methods starting with "as" are a view where as methods starting with "to" (or ending in "To" for the case of transferTo) are a copy. If the output is to be reused "as" methods should be copied or fully used before the output is reused.