从多个线程访问OkHttpClient响应

问题描述 投票:0回答:1

我想使用PipedOutputStreamPipedInputStream来传递Response body。我不太确定它在多线程方面是否安全。响应将从另一个线程访问。


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()方法是安全的吗?

java okhttp okhttp3
1个回答
1
投票

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

你可能想看看Okio的Pipe。它比java.io管道的东西更有能力。

© www.soinside.com 2019 - 2024. All rights reserved.