-4
public static MainActivity mainActivity ;

public static MainActivity instance() {
    return mainActivity  ;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_navigation);
    mainActivity  = this;

}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (mainActivity  != null) {
        mainActivity  = null;       
    }      
}

Why it will memory leak ? And why we say this writing is very bad ? I want to understand it from GC principle。

ZZJ
  • 19
  • 4
  • Possible duplicate of [Creating a memory leak with Java](http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java) – David Rawson Jan 12 '17 at 09:33
  • From an answer to the question marked as duplicate: "The class allocates a large chunk of memory (e.g. new byte[1000000]), stores a strong reference to it in a static field, and then stores a reference to itself in a ThreadLocal.". Since Activity allocates a large chunk of memory (for its views) and you are putting a strong reference in a static field, all you need to do now is have a class with a longer lifecycle reference that static field. Then you would have created the memory leak – David Rawson Jan 12 '17 at 18:13

1 Answers1

0

onDestroy is not always called and if it is not you will leak. onStop is always called, if you do set the mainActivity to null there you might not have a leak. But I wonder why you would ever need this.

also, your:

public static MainActivity instance() {
    if(mainActivity == null){
         mainActivity  = this;
    }
    return mainActivity  ;
}

Is static and uses "this", I don't think that is possible. There is no "this" in a static method.

Frank
  • 12,010
  • 8
  • 61
  • 78
  • Thanks 。“this” is my mistake ,I corrected it。In fact, I don't need it , i just know why we say this writing is so bad , and I want to understand it from GC principle. – ZZJ Jan 12 '17 at 09:05
  • well, because you cannot completely "trust" that onDestroy is called. putting it onStop might be fine but just very strange. – Frank Jan 12 '17 at 11:30