1

The java question: I have an outer class, a method of which is generating anonymous inner class. The anonymous inner class can 'outlive' the instance of the outer class. The anonymous inner class does not use ANYTHING from the outer class. Will the generated inner class still hold a reference to the outer class, preventing it from GC?

The Android question:

public class SomeActivity... {


public void onResume(){
   ....
   asyncTask.setCallback(newCallback());
}

private static Callable newCallback(){
   return new Callable()......;
}


}

Now about the method newCallback(). If it was NOT static...

As it creates a new anonymous class implementing callable, it can have an implicit reference to the outer class (the current context, Activity). As an async task is not bound to any context in android, it can outlive the Activity. And so will its members (the callback callable).And the callable can have an implicit reference to the activity, thus making the context(Activity) unavailable for GC, thus causing a probably hard to find memory leak.

My question is: If the newCallback method was not static, would the created callback hold a reference to the outer class, given that the callback does not use ANY of the Activity's stuff? Did I just dodge a bullet remembering to externalize in static method the generation of callable, so it does not hold implicit reference to activity?

George
  • 3,727
  • 9
  • 31
  • 47

0 Answers0