Merge "Workaround bad GC of tombstone watcher." into main
diff --git a/services/core/java/com/android/server/os/NativeTombstoneManager.java b/services/core/java/com/android/server/os/NativeTombstoneManager.java
index f6e7ef3..3bcaf58 100644
--- a/services/core/java/com/android/server/os/NativeTombstoneManager.java
+++ b/services/core/java/com/android/server/os/NativeTombstoneManager.java
@@ -56,6 +56,7 @@
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.lang.ref.Reference;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Optional;
@@ -73,6 +74,9 @@
 
     private final Context mContext;
     private final Handler mHandler;
+    // TODO(b/339371242): The garbage collector is misbehaving, and we must have
+    // a reference to this member outside the constructor. More details in the
+    // corresponding comment elsewhere in this class.
     private final TombstoneWatcher mWatcher;
 
     private final ReentrantLock mTmpFileLock = new ReentrantLock();
@@ -139,6 +143,14 @@
             processName = parsedTombstone.get().getProcessName();
         }
         BootReceiver.addTombstoneToDropBox(mContext, path, isProtoFile, processName, mTmpFileLock);
+
+        // TODO(b/339371242): An optimizer on WearOS is misbehaving and this member is being garbage
+        // collected as it's never referenced inside this class outside of the constructor. But,
+        // it's a file watcher, and needs to stay alive to do its job. So, add a cheap check here to
+        // force the GC to behave itself. From a technical perspective, it's possible that we need
+        // to add this trick to every single member function, but this seems to work correctly in
+        // practice and avoids polluting a lot more of this class.
+        Reference.reachabilityFence(mWatcher);
     }
 
     private Optional<TombstoneFile> handleProtoTombstone(File path, boolean addToList) {