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?


1 Answer 1

  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;
  • \$\begingroup\$ what's the purpose of having LazyHolder class when you can directly have instance object under OkSingleton class ? \$\endgroup\$ Jun 14, 2018 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, 2018 at 9:13
  • \$\begingroup\$ Thank you for help. Lazy Holder is thread-safe ? \$\endgroup\$
    – Castiel
    Jun 14, 2018 at 15:57
  • \$\begingroup\$ @Castiel Yes. It's supported by JVM. \$\endgroup\$
    – thangdc94
    Jun 15, 2018 at 1:56
  • \$\begingroup\$ how to check that it working as singleton because i got GC blocked error \$\endgroup\$
    – Ahmad
    Jul 11, 2020 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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