Video in progress
One piece of code writes data to an `OutputStream`, while another API expects it as an `InputStream`. How do you connect them without an intermediate file and without gathering everything in memory?
With a PipedOutputStream/PipedInputStream pair: the writer runs in one thread and the reader in another, with a small circular buffer between them. If you use both in a single thread you get a deadlock, and the writer's error has to be delivered to the reader separately.
📖 Answer
A typical case: you generate a CSV with a Writer, while the storage SDK asks for an InputStream to upload. ByteArrayOutputStream gathers everything on the heap, and a temporary file means disk usage and cleanup problems.
PipedInputStream in = new PipedInputStream(64 * 1024); // the default buffer is only 1024 bytes
PipedOutputStream out = new PipedOutputStream(in);
Future<?> writer = executor.submit(() -> {
try (var w = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
for (Row r : rows) { w.write(r.toCsv()); w.newLine(); }
}
return null;
});
storage.upload(key, in); // this thread reads
writer.get(); // the writer's error comes out here
When the buffer is full the writer waits, and when it is empty the reader waits: natural backpressure.
Traps:
- if you do
out.write(...)thenin.read(...)in a single thread, the writer waits forever once the buffer fills up; - if the writer thread dies with an exception, the reader gets an
IOException("Write end dead" or "Pipe broken") and the real cause is lost. That is why you needwriter.get()to get the actual error; - if the reader stops early, you must close
in, otherwise the writer hangs on a full buffer; - a 1024-byte buffer is too small by default and the threads switch too often; make it around 64 KB.
If the data is small, a plain ByteArrayOutputStream is simpler. A pipe is for large, streaming data.
Sign up to mark studied questions and save your progress.