并行调用 OkHttpClient 是线程安全的吗?
2022-09-01 03:13:50
我有几个线程同时运行,其中一些需要从Internet请求数据。我是否需要关心他们对单例的访问的同步?OkHttpClient
例如
线程 1
...
Request request = new Request.Builder()
.url("http://hell.com/siners.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Some work in Thread1
}
}
线程 2
...
Request request = new Request.Builder()
.url("http://hell.com/slutList.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Some work in Thread2
}
}
是同时发生还是有潜在危险?newCall().enque()
newCall().execute()