开发者

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
 pu开发者_开发知识库blic 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


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.


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

 static BackGroundWorker bgWorker;

instead:

BackGroundWorker bgWorker;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜