Skip to content

Memory leak: Android.Runtime.IdentityHashTargets and WeakReference<IJavaPeerable> when navigating between two or more activities #9396

Closed

Description

@mattsetaro

Android framework version

net8.0-android

Affected platform version

.NET 8.0.402

Description

I noticed this issue on .NET MAUI, and was able to track it down to here, .NET Android Runtime. There appears to be a memory leak when navigating between pages. I created a second activity with a button that when clicked calls Finish(), then in the MainActivity there's another button that navigates to the second activity.

App init, no navigations:
Image

After about 100 navigations:
Image

Steps to Reproduce

  1. Create a new .NET 8 Android application
  2. In activity_main.xml add a button
  3. In MainActivity.cs add the following code to the bottom of OnCreate():
    1. Button buttonToSecondActivity = FindViewById<Button>(Resource.Id.button);buttonToSecondActivity.Click += (sender, e) =>{ var intent = new Intent(this, typeof(SecondActivity)); StartActivity(intent);};
  4. Create a new XML layout called second_activity.xml , and add a button to the page
  5. Create a new activity called SecondActivity and at the bottom of OnCreate() add the following code:
    1. Button buttonBackToMain = FindViewById<Button>(Resource.Id.button2);buttonBackToMain.Click += (sender, e) =>{ Finish();};
  6. Run the app and click the buttons to navigate between the two pages

Here is a repo with these changes and a script to click the buttons for you: [m-script.sh](http://m-script.sh/) — run the app in an emulator, then run that script in your terminal -- https://github.com/mattsetaro/android-memory-leaks

Did you find any workaround?

No response

Relevant log output

No response

Activity

  1. added
    Area: App Runtime
    needs-triage
    on Oct 14, 2024
  2. added
    Area: Mono.Android
    and removed
    Area: App Runtime
    needs-triage
    on Oct 14, 2024
  3. mattsetaro commented on Oct 15, 2024

    @mattsetaro
    Author

    I can't help but think its related to this:

    ~Object ()
    {
    	// FIXME: need hash cleanup mechanism.
    	// Finalization occurs after a test of java persistence.  If the
    	// handle still contains a java reference, we can't finalize the
    	// object and should "resurrect" it.
    	refs_added = 0;
    	if (Environment.HasShutdownStarted) {
    		return;
    	}
    	JniEnvironment.Runtime.ValueManager.FinalizePeer (this);
    }
    
  4. jonathanpeppers commented on Nov 1, 2024

    @jonathanpeppers
    Member

    @mattsetaro your sample needs to call GC.Collect() at least once in there to be sure it's running in a determistic way:

    That being said, I've seen IdentityHashTargets in diffs of .gcdump files and wondered if there was an issue there. Is that the only type you see a problem with? What if you add a GC.Collect() call in the sample?

  5. added this to the .NET 10 milestone on Nov 1, 2024
  6. jonpryor commented on Nov 4, 2024

    @jonpryor
    Contributor

    I believe that this is less a "bug" and more a "this is how things work (for better or worse)."

    See also the Xamarin.Android Garbage Collection documentation (which really should be migrated to .NET for Android…)

    In broad strokes:

    1. Every Java.Lang.Object subclass holds a JNI Global Reference to its corresponding Java peer. This JNI Global Reference prevents the Android VM from collecting those instances.

    2. When .NET performs a GC, any Java.Lang.Object subclass instances will be added to the .NET GC Finalization Queue, but not finalized.

    3. During a subsequent GC, all Java.Lang.Object subclasses in the finalization queue are passed to the "GC Bridge", which:

      1. "Copies over" the object graph references of (2) to their corresponding Java peers.
      2. "Toggles" the JNI Global References to JNI Weak Global References.
      3. Kicks off a Java-side GC
      4. "Toggles back" the JNI Weak Global References to JNI Global References
        If this "toggle back" results in the NULL pointer, the Java peer was collected, and we inform the .NET GC that the managed peer cal be collected.
        If this "toggle back" results in a non-NULL pointer, then the Java peer is still alive, and we inform the .NET GC that the managed peer cannot be collected.

    Applying these broad strokes to your sample app:

    • The AndroidApp2.MainActivity C# instance keeps the Java peer crc64….MainActivity alive.
    • The AndroidApp2.MainActivity instance will not be collected until (1) multiple .NET GC's occur in which (2) the instance is added to the finalization queue, and (3) the instance is passed to the GC Bridge.
      This is likely at least two GCs.
    • Your app doesn't cause any GCs, at least until you've navigated between the pages a lot.

    If this is a concern, there are two things you can do:

    1. Have a GC.Collect() invocation somewhere in your Android lifecycle code.
    2. (Optional) call this.Dispose() within your MainActivity instance when you know that instance will no longer be used from Java code.
  7. jonathanpeppers commented on Nov 4, 2024

    @jonathanpeppers
    Member

    @mattsetaro we don't think there is an issue here, but let us know if you have other details. If you can add GC.Collect() calls in your app, and still see things never going away, we could investigate.

  8. locked and limited conversation to collaborators on Dec 5, 2024
  9. removed this from the .NET 10 milestone on Dec 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Area: Mono.Android

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions