The code is like below:
public class MyTestHelperHelper {
static MyTestApi storeApi = null;
public static synchronized void initial(Application application) {
if (storeApi == null) {
storeApi = new MyTestApiImplImpl();
storeApi.initiImplal(application);
}
}
public static MyTestApi getInstance() {
return storeApi;
}
}
MyTestHelperHelper's initial method is called in Application's onCreate, which is in UI thread. MyTestHelperHelper's getInstance method is called in the Activity's onCreate, which is also in UI thread.
In most case, it works normally. But sometimes, it return null with MyTestHelperHelper's getInstance, which leads to the NPE when I do further operations.
Though the case is rare, I can see it several times in the crash report. I just don't quite understand why:
There is no write to the "storeApi", except in the initial method.
Both initial and getInstance is in main thread, because initial is called in Application onCreate, and getInstance is called in Activity onCreate.
Seems the NPE occurs only when
1.process starts without application's oncreate. OR
2.When memory is low, many process data, including static variables, classloaders, classes, etc, are cleaned, except the application instance stays in the process. Is it possible?
It is not possible that a process is newly created and Application.onCreate()
is not called.
Whenever a process is created, Application.onCreate()
will be called.
However there are certain scenarios where lifetime of static variables could be impacted.
Lifecycle of static variable starts with class been loaded by the JVM and ends with class being unloaded.
A static variable will remain alive as long as one of following won't happen:
The class is unloaded due to low memory conditions.
Note: In this case Application object still persists since it will be the last object to be deallocated. This deallocation cannot be controlled by apps but determined by OS. This could happen if your app is in background and OS wants to relinquish the memory.
You can use onSaveInstanceState()
and onRestoreInstanceState()
to save and restore state of your static variable respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With