【发布时间】:2019-05-31 15:37:10
【问题描述】:
我想使用PipedOutputStream 和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() 方法是否安全?
【问题讨论】: