我想使用PipedOutputStream和PipedInputStream来传递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()
方法是安全的吗?
是!您可以将Response对象传递给其他线程。唯一的规则是您不能让多个线程同时访问响应主体。
你可能想看看Okio的Pipe。它比java.io管道的东西更有能力。