Рина Сергеева
Рина Сергеева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
OI

C++ - Test 001. The first program and data types

  • Result:40points,
  • Rating points-8
AD

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

  • Result:50points,
  • Rating points-4
m

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

  • Result:80points,
  • Rating points4
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 7:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 9:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 3:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 2:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 6:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Donald Randolph
Donald RandolphDec. 30, 2024, 10:59 a.m.
Personal Injury lawyer Santa Monica As an experienced Santa Monica personal injury lawyer, Donald C. Randolph has recovered over $100 Million in verdicts and settlements for our clients. In severe injury cases, this compensation i…
Nirvana Yoga School
Nirvana Yoga SchoolDec. 30, 2024, 1:13 p.m.
OAuth2.0 через VK, получение email Nirvana Yoga School is one of the most trusted and reputed traditional Rishikesh yoga courses , India certified by Yoga Alliance, USA. We aim to spread traditional yoga teachings so t…
s
sriparkDec. 30, 2024, 12:47 p.m.
Mobile app development company in Chennai A Mobile app development company in Chennai focuses on creating personalized mobile applications to meet various business requirements. These companies offer a full range of services,…
a
amit88Dec. 30, 2024, 12:45 p.m.
Excel in Exams with PSLE Maths Tuition Singapore Preparing for the PSLE can be challenging, but the right guidance makes all the difference. PSLE Maths tuition Singapore offers personalized coaching to help students master key concepts, improv…
a
awinash62Dec. 30, 2024, 12:23 p.m.
Unlock Your Potential with the Certified Public Accountant Credential" Becoming a Certified Public Accountant (CPA) is a career milestone that opens doors to unparalleled opportunities in the world of accounting and finance. This globally recognized qualification s…

Follow us in social networks