Is it thread-safe to make calls to OkHttpClient in parallel?

You asked a very good question, allow me to expound holistically. Based on GitBub issues opened for OkHttp, my summary is this.

Question

I believe a single instance of OkHttpClient should be reused to create multiple connections. Is OkHttpClientthread safe? If not, isOkHttpClient.open()` thread safe?

Answer

Yes. It is designed to be treated as a singleton. By using a single instance you are afforded a shared response cache, thread pool, connection re-use, etc. Definitely do this!

Question

How about thread safety? Is OkHttpClient thread safe or at least its open() function?

Answer

Yes

Conclusion

OkHttpClients should be shared

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)