Retry 2040-huge-native-alloc more aggressively

Also fix one case in which we could fail to report a recurring problem.

Bug: 190148586
Test: Treehugger
Change-Id: If516767079ff2f2a37fac200bff72d38c0090600
diff --git a/test/2040-huge-native-alloc/src/Main.java b/test/2040-huge-native-alloc/src/Main.java
index 59e1266..3c8ae23 100644
--- a/test/2040-huge-native-alloc/src/Main.java
+++ b/test/2040-huge-native-alloc/src/Main.java
@@ -24,7 +24,7 @@
   int allocated = 0;
   int deallocated = 0;
   static Object lock = new Object();
-  final static int MAX_TRIES = 4;
+  final static int MAX_TRIES = 10;
   WeakReference<BufferHolder>[] references = new WeakReference[HOW_MANY_HUGE];
 
   class BufferHolder {
@@ -61,6 +61,14 @@
       if (new Main().tryToRun(i == MAX_TRIES)) {
         break;
       }
+      if (i == MAX_TRIES / 2) {
+        // Maybe some transient CPU load is causing issues here?
+        try {
+          Thread.sleep(3000);
+        } catch (InterruptedException ignored) {
+          System.out.println("Unexpected interrupt");
+        }
+      }
       // Clean up and try again.
       Runtime.getRuntime().gc();
       System.runFinalization();
@@ -84,7 +92,10 @@
 
     if (startingGcNum != getGcNum()) {
       // Happens rarely, fail and retry.
-      return false;
+      if (!lastChance) {
+        return false;
+      }
+      System.out.println("Triggered early GC");
     }
     // One of the notifications should block for GC to catch up.
     long actualTime = timeNotifications();