dylan.kwon
dylan.kwon

Reputation: 551

BottomSheetDialogFragment memory leak (use leakcanary)

I found a Memory Leak in my PopupDialog, but I do not know why.

So I commented out all the overridden methods, but I still got a leak.

BottomSheetDialog

class PopupDialog : BottomSheetDialogFragment() {

    // Annotated all methods and variable.

}

Activity

fun showPopupDialog() = 
    PopupDialog().show(supportFragmentManager, "DialogTag.POPUP_DIALOG")

leakcanary

enter image description here

Upvotes: 5

Views: 1684

Answers (1)

Markymark
Markymark

Reputation: 2989

If you tap on the Message.obj (excluded) node you will see the following message.

Excluded by rule matching field android.os.Message#obj because A thread waiting on a blocking queue will leak the last dequeued object as a stack local reference. So when a HandlerThread becomes idle, it keeps a local reference to the last message it received. That message then gets recycled and can be used again. As long as all messages are recycled after being used, this won't be a problem, because these references are cleared when being recycled. However, dialogs create template Message instances to be copied when a message needs to be sent. These Message templates holds references to the dialog listeners, which most likely leads to holding a reference onto the activity in some way. Dialogs never recycle their template Message, assuming these Message instances will get GCed when the dialog is GCed. The combination of these two things creates a high potential for memory leaks as soon as you use dialogs. These memory leaks might be temporary, but some handler threads sleep for a long time. To fix this, you could post empty messages to the idle handler threads from time to time. This won't be easy because you cannot access all handler threads, but a library that is widely used should consider doing this for its own handler threads. This leaks has been shown to happen in both Dalvik and ART.

As suggested in the message you could post to the handler attached to the main thread's looper. You would do this after the dialog is dismissed.

A handler that is created on the main thread will be attached to the main thread's looper.

So you could do something like this existingHander.post {} or to create a new handler you could do this Handler(Looper.getMainLooper()).post {}

Source: https://github.com/square/leakcanary/blob/master/leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidExcludedRefs.java#L128

Upvotes: 2

Related Questions