Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leaked (activity leak) caused by CookieSyncManager?

Tags:

android

I used MAT tool in Eclipse to investigate a memory leak issue and found that, occasionally, a CookieSyncManager thread instance leaks my activity. The path from my activity to GC root is as following:

com.mycompany.myapp.MyActivity
  --> mContext  com.android.internal.policy.impl.PhoneFallbackEventHandler
    --> mFallbackEventHandler  android.view.ViewRoot
      --> target  android.os.Message
        --> <java local> java.lang.Thread CookieSyncManager Thread

MyActivity called CookieSyncManager.createInstance(this.getApplicationContext()); in onCreate(), but it doesn't use any webview. It only contains some animations. I don't understand why it is leaked by CookieSyncManager. Can someone help?

Thanks.

like image 710
Kai Avatar asked Oct 18 '11 17:10

Kai


1 Answers

You could call CookieSyncManager.createInstance(this.getApplicationContext()); using a context wrapper that only holds a weakreference to the actual context.

In such a case you would delegate all calls to the weakly referenced context which will automatically be cleared when there a no other strong references to it. Just make sure you perform a null check before accessing the actual context like this.

Context realContext = mMyWeakReference.get();
if (realContext != null) {
    // delegate call to real context
    realContext.delegateToWhateverFunctionWasCalled();
}

storing it in a local variable is important and could prevent an npe when the reference is cleared while your code runs.

This kinda looks like a potential framework issue, though if the framework clears this reference a bit later it should also be fine. And in that case it may not be a real issue at all, just a false positive.

like image 158
nickmartens1980 Avatar answered Nov 03 '22 12:11

nickmartens1980