Memory leak in below example.
1.SpeedHelper.java:
public class SpeedHelper {
interface Listener {
void OnSelected(String entry);
}
static Listener sListener;
static void setListener(Listener listener) {
sListener = listener;
}
static Listener getListener() {
return sListener;
}
static void clearListener() {
sListener = null;
}
}
2.CallSpeed.java
public class CallSpeed {
protected void speed() {
SpeedHelper.Listener litener = SpeedHelper.getListener();
if (litener != null) {
litener.OnSelected("mEntry");
}
}
}
3.MainActivity.java
public class MainActivity extends Activity {
private CallSpeed callspeed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SpeedHelper.setListener(mCallSpeedListener);
callspeed = new CallSpeed();
callspeed.speed();
}
private SpeedHelper.Listener mCallSpeedListener = new SpeedHelper.Listener() {
@Override
public void OnSelected(String entry) {
Toast.makeText(getApplicationContext(), entry, Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
SpeedHelper.clearListener();
}
}
How to avoid Memory leak for “sListener”?
Your problem lies in the following non-static enclosed anonymous class in association with the static field
sListener:Because this is a non-static enclosed class, it contains a reference to its outer class,
MainActivity. This hidden reference blocks the release of theMainActivityclass by the GC because the objectmCallSpeedListener– which contains the hidden reference – get stored in the static fieldsListenerwith the instructionSpeedHelper.setListener(mCallSpeedListener);. Therefore, theMainActivityobject is never collected, itsonDestroyfunction is never called and everything remains in memory; out of reach of the GC. Using static fields is a door wide open to memory leaks and the presence of hidden references in enclosed classes (anonymous or not) amplifies this problem.In your case, you will have to either remove the static field
sListeneror change the anonymous class to an ordinary class; one without the hidden reference to its outerMainActivityclass or make a direct call toclearListenerin another callback of the activity when it is terminated.