2
\$\begingroup\$

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?

\$\endgroup\$
2
\$\begingroup\$
  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;
    }
}
\$\endgroup\$
  • \$\begingroup\$ what's the purpose of having LazyHolder class when you can directly have instance object under OkSingleton class ? \$\endgroup\$ – Jabbar_Jigariyo Jun 14 '18 at 7:04
  • 1
    \$\begingroup\$ @Jabbar_Jigariyo TL;DR, to remove synchronized. More detail: en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom \$\endgroup\$ – thangdc94 Jun 14 '18 at 9:13
  • \$\begingroup\$ Thank you for help. Lazy Holder is thread-safe ? \$\endgroup\$ – Castiel Jun 14 '18 at 15:57
  • \$\begingroup\$ @Castiel Yes. It's supported by JVM. \$\endgroup\$ – thangdc94 Jun 15 '18 at 1:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.