Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why kotlin by lazy can cause memory leak in android?

I define a loading Dialog like this

private val loadingDialog: LoadingDialog by lazy { LoadingDialog() }

loadingDialog is a DialogFragment

when I use leakcanary to watch my app, I find the loadingDialog cause memory

Can somebody help me?

like image 792
wanbo Avatar asked Aug 07 '18 04:08

wanbo


People also ask

What causes memory leaks in Android?

Memory leaks occur when an application allocates memory for an object, but then fails to release the memory when the object is no longer being used. Over time, leaked memory accumulates and results in poor app performance and even crashes.

What is memory leak Kotlin?

A memory leak happens when your code allocates memory for an object, but never deallocates it. This can happen for many reasons. You'll learn these causes later. No matter the cause, when a memory leak occurs the Garbage Collector thinks an object is still needed because it's still referenced by other objects.

Why lazy is used in Kotlin?

Lazy is mainly used when you want to access some read-only property because the same object is accessed throughout. That's it for this blog.

What are the causes of memory leaks?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.


1 Answers

When you define a val delegated by lazy {...}, the lambda you pass to the delegate captures the scope into its closure (though it's only the outer this in your case, it may be an Activity instance).

Then the delegate instance holds the references it captured until the moment the val is first accessed. Then it invokes the lambda and 'forgets' the closure.

But if your val is accessed too late (or never), the lambda's closure may keep the objects in memory that would otherwise be disposed, which is a possible memory leak.

like image 148
hotkey Avatar answered Oct 16 '22 20:10

hotkey