Prevent memory leaks with static classes

Gespeichert von pterodactylus42 am

As cuixiaoyiyi puts it on github: "An anonymous inner class will hold a reference to the this pointer of the outer class and will not be released until the thread ends. It will hold the Activity and prevent its timely release."

The effect on garbage collection of the outer class is obvious. In my case, the anonymous inner class is a runnable that holds references to some gui elements it should update. Exceptions can occur if the referenced Activity is closed by the user, while the runnable is still in the queue and waiting to be executed.

A solution can be to use a static class with a weak reference as referencing object, which is the runnable in this case.

This exemplifies that one major meaning of the keyword static is: not bearing a reference to a current instance. It would even be a compile time error if a static class contains a usage of a non-static member of an enclosing class.