I use the singleton approach for a subclass of Application. I use the following:
public class MyApplication extends Application {
private static MyApplication instance;
public MyApplication() {
instance = this;
}
public static MyApplication getInstance() {
if (instance == null) {
synchronized (MyApplication.class) {
if (instance == null)
new MyApplication();
}
}
return instance;
}
...
...
My question is: If the instance is assigned once, during the initial call to the class creator by the system, the instance should never be null after! So if (instance == null)
inside getInstance()
will never returns true. Or am I wrong?
EDIT:
I correct the code as found on wikipedia:
public class volatile MyApplication extends Application {
private static MyApplication instance;
public MyApplication() {
}
public static MyApplication getInstance() {
if (instance == null) {
synchronized (MyApplication.class) {
if (instance == null)
instance = new MyApplication();
}
}
return instance;
}
...
...
Added volatile
and instance = new MyApplication();
Is it correct? My question still remains...