简体   繁体   中英

Memory leak: Confusion between Java Garbage Collector - and Android killing mechanism?

I am newbie to both Java and Android, and currently I am confused about "memory leak" in Android, for example: I have 01 Class, 01 Activity and 01 Interface as following:

Class BackGroundWorker is a singleton, which lives as long as the application lives:

public class BackGroundWorker {
 private IOnEventOccurListener listener = null;
 private static BackGroundWorker instance;
// ....
 public void setListener(IOnEventOccurListener pListener) {
  this.listener =  pListener;
 }
// ....
 public static BackGroundWorker getInstance() {
  //...
  return instance;
 }
}

The Listener Interface:

public interface IOnEventOccurListener {
 public void onEventOccur();
}

And the Listener itself (An activity):

public class ShowSomething extends Activity implements IOnEventOccurListener{

 BackGroundWorker bgWorker;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  bgWorker = BackGroundWorker.getInstance();
  bgWorker.setListener(this);
 }

 @Override
 public void onEventOccur() {
  // TODO do something

 }
}

Now, according to what Romain Guy mentioned here : It's a memory leak, because there's a reference to the listener (Activity). So Java GC cannot collect the Activity, even when it's not in use.

I was able to solve that problem by WeakReference – but still wonder: In this case, when the device needs more memory, according to Android Dev document, it will “kill” the activity if needed - assuming that the Activity ShowSomething is “killed” – then what happens ? (It's still leak according to Romain Guy, and still “killed” )

I am really confused. Could anybody please explain this ?

Thank you in advanced,
Son

I think it would have the leak if we will use:

 static BackGroundWorker bgWorker;

instead:

BackGroundWorker bgWorker;

Android will destroy activities that are not on the screen to try to free up memory. However, GC rules still apply, and hence your static reference to the activity prevents the memory from being freed.

Eventually, Android will terminate the whole process. At that point, your leaked memory will be freed. However, in between your activity being destroyed and the process being terminated, you are wasting RAM.

Rather than use WeakReference , please null out the static reference when the activity is destroyed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM