Рина Сергеева
Рина СергееваDec. 27, 2018, 1:53 a.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.

public class LeakingRunnable implements Runnable {

    private View view;

    LeakingRunnable(View view){       //don't do that!
        this.view = view;
    }
    @Override
    public void run() {
        // do some work
    }
}

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:

public class NoLeakingRunnable implements Runnable {

    @NonNull
    private final WeakReference<View> viewRef;

    public NoLeakingRunnable(@NonNull View view){
        this.viewRef = new WeakReference<>(view);         //do that!
    }
    @Override
    public void run() {
        View view = viewRef.get();
        // do some work
    }
}  

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.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 23, 2024, 3:51 p.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks