To mitigate memory leaks we keep a weak reference of an activity in an inner class running on different thread. We check weakreference.get() is non null and then only proceed further. What if when we checked weakreference.get() was non null but garbage collection happened, do we need to check if the reference is non null again and again or am I missing something?
public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MyAsyncTask(this).execute();
}
private static class MyAsyncTask extends AsyncTask {
private WeakReference<MainActivity> mainActivity;
public MyAsyncTask(MainActivity mainActivity) {
this.mainActivity = new WeakReference<>(mainActivity);
}
@Override
protected Object doInBackground(Object[] params) {
return doSomeStuff();
}
@Override
protected void onPostExecute(Object object) {
super.onPostExecute(object);
if (mainActivity.get() != null){
//do something
//context switching and garbage collection happen
//again do a null check?
}
}
}
}