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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With