Last Updated:

Rules for releasing Kotlin objects

One of the most important features of Java and Kotlin is automatic memory management, when the garbage collector itself removes unused objects from RAM. The garbage collector greatly simplifies the life of developers, but it does not always work.

RECOMMEND:

  • Optimizing application loading in Kotlin
  • A modern approach to development with Kotlin
  • How to make Kotlin code more understandable

A canonical example where a garbage collector fails is Android activity. Consider the following example:

 

The developer decided to simplify his life and took out the function logError in companion objectto always have access to it. The only problem here is that logError internally refers to MainActivity. As a result, if MainActivity if it is complete, it will continue to occupy memory—the garbage collector will not be able to release it because there is a link to activity in the companion object.

you can resolve this issue by replacing the hard-coded reference with WeakReference (although a good problem is solved with the help of a dependency injection system).

Another example is the stack implementation:

 

It is absolutely correct, except for one point: the function pop() does not remove an element from the array. This means that if you create a stack of 1000 items and then delete 999 of them, the stack will still take up the memory needed to store 1000 items. The code is fixed like this:

How to detect such problems? It is worth learning how to use the hip analyzer (there is one in the standard Android Studio delivery). The LeakCanary tool will also help. It will automatically notify you of any leaks of activity.