0

I would like to use PipedOutputStream and PipedInputStream to stream Response body. I am not quite sure if it is safe in terms of multithreading. The response will be accessed from a different thread.


public Streamer execute() {
    Response response = null;
    try {
        Call call = client.newCall(request);
        response = call.execute();
        return stream(response);
    } catch (Exception e) {
        if (response != null) response.close();
    }
}

@FunctionalInterface
interface Streamer {
    void write(OutputStream out) throws Exception;
}

private static Streamer stream(Response response) throws IOException {

    return out -> {
        // will be executed from a different thread
        try (BufferedSource source = response.body().source();
            Buffer buffer = new Buffer()) {

            BufferedSink sink = Okio.buffer(Okio.sink(out));
            long readBytes;
            long readTotal = 0;
            while ((readBytes = source.read(buffer, BUFFER_SIZE)) != -1) {
                sink.write(buffer, readBytes);
                sink.flush();
                readTotal += readBytes;
            }
        }
    };
}

It is safe to pass Response object to a different thread and access body() and body().close() methods?

1 Answer 1

1

Yes! You can pass Response objects to other threads. The only rule is you can’t have multiple threads accessing the response body at the same time.

You might want to look at Pipe in Okio. It's a bit more capable than the java.io pipe thingies.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.