Why does this code wait 1000ms instead of 500ms?

Viewed 114

I don't understand how this code prints 1000 instead of 500. Is there something I am missing?

    PipedOutputStream writer = new PipedOutputStream();
    PipedInputStream reader = new PipedInputStream();
    writer.connect(reader);
    BufferedReader stream = new BufferedReader(new InputStreamReader(reader));

    ScheduledExecutorService thread = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().build());
    thread.schedule(() -> {
        try {
            Thread.sleep(500);
            writer.write("test\n".getBytes(StandardCharsets.UTF_8));
        } catch (InterruptedException | IOException ignored) {
        }
    }, 0, TimeUnit.MILLISECONDS);

    long startTime = System.currentTimeMillis();
    stream.readLine();
    long duration = System.currentTimeMillis() - startTime;
    System.out.println(duration);
1 Answers

Assuming that PipedOutputStream is a subclass of OutputStream, in the given code it is never flushed.

Since we don't know the exact caching or flushing behavior of PipedOutputstream it may happen that the bytes for test\n are not written to the connected PipedInputStream immediately after the wait process of 500 ms has completed. Instead it forwards the first chunk of data to its connected sink at some later point.

Again, assuming that PipedOutputStream is a subclass of OutputStream, flushing the stream will fix this behaviour.

try {
    Thread.sleep(500);
    writer.write("test\n".getBytes(StandardCharsets.UTF_8));
    writer.flush();
} catch (InterruptedException | IOException ignored) {
}
Related