Рина Сергеева
Dec. 27, 2018, 12:53 p.m.

A little about memory leaks and ways to avoid them

What is memory Leaks in Android development ?

The application creates objects, they lie in memory and can not clean out after the completion of its work.

Why is this happening ?

Java has its own means of clearing memory from unused items. This is garbage collection .

The garbage collector marks all objects that can be deleted if they are not referenced. Memory leak - this is just a lost reference, which shows that the object can not be deleted.

The complexity of this bug is that until a certain time it is not visible and it can not interfere.
There's a good quote from Benjamin Franklin: “A small leak will sink a great ship."
Memory leaks take the RAM of the application. The amount of raw memory will grow and may one day cause your app to slow down and crash . This will lead to user dissatisfaction and most likely the app will be removed...


One of the most dangerous when a program loses a link to view . It would seem that this view is small on the screen. However, it is worth remembering that view has a link to Activity (Fragment). And if the link to view is not removed, then Activity (Fragment) is also alive. A Activity (Fragment) has links to all the views on the screen.

How do I know if there are memory leaks ?

You can find leekie's memory in different ways. But the easiest way is to use Profiler Android studio.

Order of actions:

  • Startup project
  • In the lower pane, click "Profiler"
  • Choose " Memory"
  • Press "Force Garbage Collection" (then you need to wait a bit)
  • Click " Dump Java heap"
  • Filter the list by the required classes
  • See the number of objects

The picture above shows that there are four Activity objects. This happened because the programmer allowed the program to lose references to view . And users love to rotate the phone screen. With each change of orientation, the activity was recreated, and the old one remained lying in the depths of memory.

If you want a way to catch memory leaks more interesting, then I suggest you familiarize yourself with the library LeakCanary .

How to avoid memory leaks ?

Here are some tips:

1. Do not create static view links. Static fields have the same lifecycle as your application.

2.Do not pass links to entities that live longer than the object you passed. For example: do not pass Runnable references to View to the class, as the new thread will continue to live even after re-creating the activity.

  1. public class LeakingRunnable implements Runnable {
  2.  
  3. private View view;
  4.  
  5. LeakingRunnable(View view){ //don't do that!
  6. this.view = view;
  7. }
  8. @Override
  9. public void run() {
  10. // do some work
  11. }
  12. }

And how to transfer view to Runnable ?

Use other types of links.
In Java, besides the usual "hard links" , there are other "soft links" and "weak" . Correctly their to call:

  • WeakReference
  • SoftReference
  • Phantom Reference

The presence of" soft links " will no longer prevent the garbage collector from removing Activity. You can read more about them here: differences between weak, soft, phantom and normal links in Java

Without memory leaks, the code above would look like this:

  1. public class NoLeakingRunnable implements Runnable {
  2.  
  3. @NonNull
  4. private final WeakReference<View> viewRef;
  5.  
  6. public NoLeakingRunnable(@NonNull View view){
  7. this.viewRef = new WeakReference<>(view); //do that!
  8. }
  9. @Override
  10. public void run() {
  11. View view = viewRef.get();
  12. // do some work
  13. }
  14. }

3. Need to make inner classes static Activity. The internal activity class about accessing the view (and any other objects) creates synthetic references to this object. And if the inner class lives longer than the activity, then Memory leak appears.

This article has been told only a small part of the information about what is a memory leak in Android development and the simplest methods to avoid them. There are still many difficult situations. Some of them will be discussed in the following articles. Subscribe to new articles.

By article asked0question(s)

2

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…