code: private static void tryWaitingForGC() {
      // We could try to preallocate memory mx bean and count collections...
      // there is no guarantee it doesn't allocate stuff too though.
      final long timeout = System.currentTimeMillis() + 2000;
      while (System.currentTimeMillis() < timeout) {
        System.gc(); 
        try {
          Thread.sleep(250);
        } catch (InterruptedException e) {
          break;
        }
      }
    }
docs: Try waiting for a GC to happen. This is a dirty heuristic but if we're
  here we're neck deep in sh*t anyway (OOMs all over).