gpt4 book ai didi

java - 并行调用 OkHttpClient 是线程安全的吗?

转载 作者:太空狗 更新时间:2023-10-29 22:54:28 29 4
gpt4 key购买 nike

我有几个同时运行的线程,其中一些需要从 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() 是否有潜在危险?

最佳答案

你问的很好,我来综合一下。基于为 OkHttp 打开的 GitBub 问题,我的总结是这样的。

问题

我认为应该重用 OkHttpClient 的单个实例来创建多个连接。 OkHttpClient线程安全吗?如果不是,OkHttpClient.open()` 线程安全吗?

回答

是的。它旨在被视为单例。通过使用单个实例,您可以获得共享响应缓存、线程池、连接重用等。一定要这样做!

问题

线程安全怎么样? OkHttpClient 是线程安全的还是至少是它的 open() 函数?

回答

结论

OkHttpClient应该共享

OkHttp performs best when you create a single OkHttpClient instance and reuse it for all of your HTTP calls. This is because each client holds its own connection pool and thread pools. Reusing connections and threads reduces latency and saves memory. Conversely, creating a client for each request wastes resources on idle pools.

关于java - 并行调用 OkHttpClient 是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48532860/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com