Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting

A little about memory leaks and ways to avoid them

Memory leaks, garbage collection, Java

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;
    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 {

    private final WeakReference<View> viewRef;

    public NoLeakingRunnable(@NonNull View view){
        this.viewRef = new WeakReference<>(view);         //do that!
    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.


Only authorized users can post comments.
Please, Log in or Sign up
Jan. 20, 2019, 6:39 p.m.
Ivan Otreshko

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

  • Result:0points,
  • Rating points-10
Jan. 20, 2019, 3:27 p.m.
Ivan Otreshko

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

  • Result:0points,
  • Rating points-10
Jan. 17, 2019, 11:51 a.m.

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

  • Result:20points,
  • Rating points-10
Last comments
Jan. 16, 2019, 8:06 a.m.

Заработало. Забыл model->select(); вписать.
Jan. 16, 2019, 8:02 a.m.

Всё равно пусто, хотя строка с данными в базу добавляется.
Jan. 16, 2019, 7:51 a.m.
Евгений Легоцкой

потому, что нужно сохранять информацию для всех остальных ролей и столбцов через вызов переопределённого метода. Да к тому же вы ещё и зациклили вызов метода data. QVariant MySqlTableModel:...
Jan. 16, 2019, 7:43 a.m.

Сделал вот так. В tableView ничего нет, кроме заголовка. QVariant MySqlTableModel::data(const QModelIndex &index, int role) const{ if (role == Qt::DisplayRole) { QTime ...
Now discuss on the forum
Jan. 21, 2019, 9:32 p.m.
Евгений Легоцкой

Добрый день. Потому, что C# и Java библиотеки внутри имеют байт-код, а не компилированные исходники в машинном коде, как в C++. Для их использования нужен JIT-компилятор, который на лету...
Jan. 21, 2019, 9:16 p.m.
Евгений Легоцкой

День добрый. Я у себя это дело запустил. Но у меня оба варианта заработало. Но у меня версия Qt была 5.11.2. Из-за этого версия Qt Quick 2.12,которую вы использовали, не нашлась. Я...
Jan. 21, 2019, 4:24 p.m.

Нашел ссылку на древние типы данных , а тут нынешние их аналоги.Но все равно каое что непоня:что такое : LPCTSTR, CALLBACK (наверно QDialig),IDOK, EDITSTREAM, TCHARКод...
Jan. 21, 2019, 2:30 p.m.
Евгений Легоцкой

Порядок создания тем - пункт 4
Jan. 21, 2019, 7:36 a.m.
Евгений Легоцкой

Добрый день! Из ваего вопроса понятна первая часть. На сайте есть статья по динамическому созданию виджетов, посмотрите её для начала - Динамическое создание виджетов . ...
Join us in social networks

For registered users on the site there is a minimum amount of advertising