Peter Jurkovic
Peter Jurkovic

Reputation: 2896

Accessing OkHttpClient Response from multiple threads

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?

Upvotes: 0

Views: 434

Answers (1)

Jesse Wilson
Jesse Wilson

Reputation: 40593

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.

Upvotes: 1

Related Questions