从多个线程访问 OkHttpClient Response

Accessing OkHttpClient Response from multiple threads

我想使用 PipedOutputStream and PipedInputStream 流式传输响应正文。我不太确定它在多线程方面是否安全。将从不同的线程访问响应。


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;
            }
        }
    };
}

Response 对象传递给不同的线程并访问 body()body().close() 方法是否安全?

是的!您可以将 Response 对象传递给其他线程。唯一的规则是你不能让多个线程同时访问响应主体。

您可能想看看 Okio 中的 Pipe。它比 java.io 管道东西更强大。