Adam Siemion
Adam Siemion

Reputation: 16039

How to force flush of OutputStream/Writer in Spring Boot

I have a Spring MVC controller which directly writes to Writer.

@GetMapping("/delay")
void delay(final java.io.Writer writer) throws IOException, InterruptedException {
    for (int i = 0; i < 10000; i++) {
        writer.write(String.valueOf(i));
        writer.write(",");
        writer.flush();

        Thread.sleep(10);
    }
}

When I call this method using curl, despite calling flush() in every loop iteration, it seems Writer is only flushed when 1024 bytes are written. Is there a way to force flushing of Writer in every loop iteration?

Upvotes: 0

Views: 1472

Answers (2)

Jeremy Grand
Jeremy Grand

Reputation: 2370

It seems to me that the CoyoteWriter flushing works fine. I guess a proper unit test would be more convincing that calling a controller with Curl.

I naively tested your code with both curl and a web browser and indeed, curl is outputing the response in bulks whereas the browser is properly reading the response as it is being written.

Upvotes: 2

Adam Siemion
Adam Siemion

Reputation: 16039

It seems it was curl which was doing caching, option --no-buffer (-N) disables the buffering of the output stream.

Upvotes: 2

Related Questions