Implementation of an OkHttp singleton for Android

Posted on

Problem

I’m new to Android programming. I am going to make lots of HTTP requests: 500, 1k, 2k, 10k.

I have tried to create a singleton class for OkHttp. I wrote this:

public class OkSingleton extends OkHttpClient {

private  static  OkSingleton minstance;
private final OkHttpClient myClient;

private OkSingleton (){
    myClient= new OkHttpClient();
}

public static synchronized  OkSingleton getMinstance(){

    if (minstance==null){
        minstance=new OkSingleton();
    }

    return minstance;
}}

Can you show me my mistakes?

Solution

  1. You don’t need to create new instance of OkHttpClient. Remove it.

  2. You can use Initialization-on-demand holder pattern to create singleton in Java. No need to use synchronized block

  3. Change coding style in your code. Remove m before instance variable. See naming convention.

Here is the code:

public class OkSingleton extends OkHttpClient {
    private static class LazyHolder {
        private static final OkSingleton instance = new OkSingleton();
    }

    public static OkSingleton getInstance() {
        return LazyHolder.instance;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *