[JAVA] OkHttp3 should be a singleton

Introduction

The connection pool part has changed significantly between OkHttp2 and OkHttp3. Quoted from Change Log.

There is no longer a global singleton connection pool. In OkHttp 2.x, all OkHttpClient instances shared a common connection pool by default. In OkHttp 3.x, each new OkHttpClient gets its own private connection pool. Applications should avoid creating many connection pools as doing so prevents connection reuse. Each connection pool holds its own set of connections alive so applications that have many pools also risk exhausting memory!

As you can see from the above, the connection pool was shared up to OkHttp2, but from OkHttp3, each instance has a separate connection pool. If you continue to instantiate OkHttp without knowing it, you may get an OutOfMemoryError. So OkHttp3 should be written in a singleton.

Sample code

For the time being, I wrote it in a singleton. Please comment if you would like to do more like this.

OkHttpSingleton.java



import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpSingleton {

    private OkHttpClient mOkHttpClient;

    private static OkHttpSingleton ourInstance = new OkHttpSingleton();

    public static OkHttpSingleton getInstance() {
        return ourInstance;
    }

    private OkHttpSingleton() {

        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
        okHttpBuilder.connectTimeout(20, TimeUnit.SECONDS);
        okHttpBuilder.readTimeout(15, TimeUnit.SECONDS);
        okHttpBuilder.writeTimeout(15, TimeUnit.SECONDS);
        okHttpBuilder.addInterceptor(getInterceptor());

        mOkHttpClient = okHttpBuilder.build();
    }

    private Interceptor getInterceptor() {

        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request newRequest = chain.request().newBuilder()
                        .addHeader("Accept", "application/json")
                        .build();

                return chain.proceed(newRequest);
            }
        };
    }

    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }
}

If you want to use the same request header, you can use the Interceptor of OkHttpClient.

If you want to change the OkHttpClient settings (timeout time, etc.) individually, rewrite them using OkHttpClient.newBuilder ().


OkHttpClient copy = client.newBuilder()
          .readTimeout(500, TimeUnit.MILLISECONDS)
          .build();

reference

Recommended Posts

OkHttp3 should be a singleton
Programming can be a god.
How software development learning should be
Java Calendar is not a singleton.
To not be a static uncle
Settings that should be done when operating a production environment with Rails