Memory Leak With Timer
I am using a timer that is canceled and restarted on a listener event. It all works fine except that the the timer thread leaks the whole outer class. My timer implementation is as
Solution 1:
If you think that the problem is that the anonymous inner class holds a reference to the outer class, then simply use a static named inner class - this will hold no reference. Put something like this inside your class:
staticclassMyTimerTaskextendsTimerTask {
private OnHeaderMovingCallBack mCallback;
int newToolbarTranslationY;
publicMyTimerTask(OnHeaderMovingCallBack mCallback, int newToolbarTranslationY) {
this.mCallback = mCallback;
this.newToolbarTranslationY = newToolbarTranslationY;
}
@Overridepublicvoidrun() {
mCallback.onHeaderMoving(newToolbarTranslationY);
}
}
Solution 2:
I have the same problem with you. I found that when I define Timer
as global var and don't set it to null
when the activity finished, it always leads memory leak.
And when I define Timer
as local var or set it to null
, the problem gone.But I don't understand why. If you had solved it, please tell me your solution, thanks!
publicclassTestActivityextendsAppCompatActivity {
privateTimer mTimer;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mTimer = newTimer();
mTimer.schedule(newTimerTask() {
@Overridepublicvoidrun() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 0);
}
@OverrideprotectedvoidonDestroy() {
super.onDestroy();
mTimer = null;
}
}
Post a Comment for "Memory Leak With Timer"