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
-
You don’t need to create new instance of
OkHttpClient
. Remove it. -
You can use Initialization-on-demand holder pattern to create singleton in Java. No need to use
synchronized
block -
Change coding style in your code. Remove
m
beforeinstance
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;
}
}