001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.testing;
018
019import static java.util.concurrent.TimeUnit.SECONDS;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.GwtIncompatible;
023import com.google.errorprone.annotations.DoNotMock;
024import com.google.j2objc.annotations.J2ObjCIncompatible;
025import java.lang.ref.WeakReference;
026import java.util.Locale;
027import java.util.concurrent.CancellationException;
028import java.util.concurrent.CountDownLatch;
029import java.util.concurrent.ExecutionException;
030import java.util.concurrent.Future;
031import java.util.concurrent.TimeoutException;
032
033/**
034 * Testing utilities relating to garbage collection finalization.
035 *
036 * <p>Use this class to test code triggered by <em>finalization</em>, that is, one of the following
037 * actions taken by the java garbage collection system:
038 *
039 * <ul>
040 *   <li>invoking the {@code finalize} methods of unreachable objects
041 *   <li>clearing weak references to unreachable referents
042 *   <li>enqueuing weak references to unreachable referents in their reference queue
043 * </ul>
044 *
045 * <p>This class uses (possibly repeated) invocations of {@link java.lang.System#gc()} to cause
046 * finalization to happen. However, a call to {@code System.gc()} is specified to be no more than a
047 * hint, so this technique may fail at the whim of the JDK implementation, for example if a user
048 * specified the JVM flag {@code -XX:+DisableExplicitGC}. But in practice, it works very well for
049 * ordinary tests.
050 *
051 * <p>Failure of the expected event to occur within an implementation-defined "reasonable" time
052 * period or an interrupt while waiting for the expected event will result in a {@link
053 * RuntimeException}.
054 *
055 * <p>Here's an example that tests a {@code finalize} method:
056 *
057 * <pre>{@code
058 * final CountDownLatch latch = new CountDownLatch(1);
059 * Object x = new MyClass() {
060 *   ...
061 *   protected void finalize() { latch.countDown(); ... }
062 * };
063 * x = null;  // Hint to the JIT that x is stack-unreachable
064 * GcFinalization.await(latch);
065 * }</pre>
066 *
067 * <p>Here's an example that uses a user-defined finalization predicate:
068 *
069 * <pre>{@code
070 * final WeakHashMap<Object, Object> map = new WeakHashMap<>();
071 * map.put(new Object(), Boolean.TRUE);
072 * GcFinalization.awaitDone(new FinalizationPredicate() {
073 *   public boolean isDone() {
074 *     return map.isEmpty();
075 *   }
076 * });
077 * }</pre>
078 *
079 * <p>Even if your non-test code does not use finalization, you can use this class to test for
080 * leaks, by ensuring that objects are no longer strongly referenced:
081 *
082 * <pre>{@code
083 * // Helper function keeps victim stack-unreachable.
084 * private WeakReference<Foo> fooWeakRef() {
085 *   Foo x = ....;
086 *   WeakReference<Foo> weakRef = new WeakReference<>(x);
087 *   // ... use x ...
088 *   x = null;  // Hint to the JIT that x is stack-unreachable
089 *   return weakRef;
090 * }
091 * public void testFooLeak() {
092 *   GcFinalization.awaitClear(fooWeakRef());
093 * }
094 * }</pre>
095 *
096 * <p>This class cannot currently be used to test soft references, since this class does not try to
097 * create the memory pressure required to cause soft references to be cleared.
098 *
099 * <p>This class only provides testing utilities. It is not designed for direct use in production or
100 * for benchmarking.
101 *
102 * @author mike nonemacher
103 * @author Martin Buchholz
104 * @since 11.0
105 */
106@Beta
107@GwtIncompatible
108@J2ObjCIncompatible // gc
109public final class GcFinalization {
110  private GcFinalization() {}
111
112  /**
113   * 10 seconds ought to be long enough for any object to be GC'ed and finalized. Unless we have a
114   * gigantic heap, in which case we scale by heap size.
115   */
116  private static long timeoutSeconds() {
117    // This class can make no hard guarantees.  The methods in this class are inherently flaky, but
118    // we try hard to make them robust in practice.  We could additionally try to add in a system
119    // load timeout multiplier.  Or we could try to use a CPU time bound instead of wall clock time
120    // bound.  But these ideas are harder to implement.  We do not try to detect or handle a
121    // user-specified -XX:+DisableExplicitGC.
122    //
123    // TODO(user): Consider using
124    // java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage()
125    //
126    // TODO(user): Consider scaling by number of mutator threads,
127    // e.g. using Thread#activeCount()
128    return Math.max(10L, Runtime.getRuntime().totalMemory() / (32L * 1024L * 1024L));
129  }
130
131  /**
132   * Waits until the given future {@linkplain Future#isDone is done}, invoking the garbage collector
133   * as necessary to try to ensure that this will happen.
134   *
135   * @throws RuntimeException if timed out or interrupted while waiting
136   */
137  public static void awaitDone(Future<?> future) {
138    if (future.isDone()) {
139      return;
140    }
141    final long timeoutSeconds = timeoutSeconds();
142    final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds);
143    do {
144      System.runFinalization();
145      if (future.isDone()) {
146        return;
147      }
148      System.gc();
149      try {
150        future.get(1L, SECONDS);
151        return;
152      } catch (CancellationException | ExecutionException ok) {
153        return;
154      } catch (InterruptedException ie) {
155        throw new RuntimeException("Unexpected interrupt while waiting for future", ie);
156      } catch (TimeoutException tryHarder) {
157        /* OK */
158      }
159    } while (System.nanoTime() - deadline < 0);
160    throw formatRuntimeException("Future not done within %d second timeout", timeoutSeconds);
161  }
162
163  /**
164   * Waits until the given predicate returns true, invoking the garbage collector as necessary to
165   * try to ensure that this will happen.
166   *
167   * @throws RuntimeException if timed out or interrupted while waiting
168   */
169  public static void awaitDone(FinalizationPredicate predicate) {
170    if (predicate.isDone()) {
171      return;
172    }
173    final long timeoutSeconds = timeoutSeconds();
174    final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds);
175    do {
176      System.runFinalization();
177      if (predicate.isDone()) {
178        return;
179      }
180      CountDownLatch done = new CountDownLatch(1);
181      createUnreachableLatchFinalizer(done);
182      await(done);
183      if (predicate.isDone()) {
184        return;
185      }
186    } while (System.nanoTime() - deadline < 0);
187    throw formatRuntimeException(
188        "Predicate did not become true within %d second timeout", timeoutSeconds);
189  }
190
191  /**
192   * Waits until the given latch has {@linkplain CountDownLatch#countDown counted down} to zero,
193   * invoking the garbage collector as necessary to try to ensure that this will happen.
194   *
195   * @throws RuntimeException if timed out or interrupted while waiting
196   */
197  public static void await(CountDownLatch latch) {
198    if (latch.getCount() == 0) {
199      return;
200    }
201    final long timeoutSeconds = timeoutSeconds();
202    final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds);
203    do {
204      System.runFinalization();
205      if (latch.getCount() == 0) {
206        return;
207      }
208      System.gc();
209      try {
210        if (latch.await(1L, SECONDS)) {
211          return;
212        }
213      } catch (InterruptedException ie) {
214        throw new RuntimeException("Unexpected interrupt while waiting for latch", ie);
215      }
216    } while (System.nanoTime() - deadline < 0);
217    throw formatRuntimeException(
218        "Latch failed to count down within %d second timeout", timeoutSeconds);
219  }
220
221  /**
222   * Creates a garbage object that counts down the latch in its finalizer. Sequestered into a
223   * separate method to make it somewhat more likely to be unreachable.
224   */
225  private static void createUnreachableLatchFinalizer(final CountDownLatch latch) {
226    new Object() {
227      @Override
228      protected void finalize() {
229        latch.countDown();
230      }
231    };
232  }
233
234  /**
235   * A predicate that is expected to return true subsequent to <em>finalization</em>, that is, one
236   * of the following actions taken by the garbage collector when performing a full collection in
237   * response to {@link System#gc()}:
238   *
239   * <ul>
240   *   <li>invoking the {@code finalize} methods of unreachable objects
241   *   <li>clearing weak references to unreachable referents
242   *   <li>enqueuing weak references to unreachable referents in their reference queue
243   * </ul>
244   */
245  @DoNotMock("Implement with a lambda")
246  public interface FinalizationPredicate {
247    boolean isDone();
248  }
249
250  /**
251   * Waits until the given weak reference is cleared, invoking the garbage collector as necessary to
252   * try to ensure that this will happen.
253   *
254   * <p>This is a convenience method, equivalent to:
255   *
256   * <pre>{@code
257   * awaitDone(new FinalizationPredicate() {
258   *   public boolean isDone() {
259   *     return ref.get() == null;
260   *   }
261   * });
262   * }</pre>
263   *
264   * @throws RuntimeException if timed out or interrupted while waiting
265   */
266  public static void awaitClear(final WeakReference<?> ref) {
267    awaitDone(
268        new FinalizationPredicate() {
269          @Override
270          public boolean isDone() {
271            return ref.get() == null;
272          }
273        });
274  }
275
276  /**
277   * Tries to perform a "full" garbage collection cycle (including processing of weak references and
278   * invocation of finalize methods) and waits for it to complete. Ensures that at least one weak
279   * reference has been cleared and one {@code finalize} method has been run before this method
280   * returns. This method may be useful when testing the garbage collection mechanism itself, or
281   * inhibiting a spontaneous GC initiation in subsequent code.
282   *
283   * <p>In contrast, a plain call to {@link java.lang.System#gc()} does not ensure finalization
284   * processing and may run concurrently, for example, if the JVM flag {@code
285   * -XX:+ExplicitGCInvokesConcurrent} is used.
286   *
287   * <p>Whenever possible, it is preferable to test directly for some observable change resulting
288   * from GC, as with {@link #awaitClear}. Because there are no guarantees for the order of GC
289   * finalization processing, there may still be some unfinished work for the GC to do after this
290   * method returns.
291   *
292   * <p>This method does not create any memory pressure as would be required to cause soft
293   * references to be processed.
294   *
295   * @throws RuntimeException if timed out or interrupted while waiting
296   * @since 12.0
297   */
298  public static void awaitFullGc() {
299    final CountDownLatch finalizerRan = new CountDownLatch(1);
300    WeakReference<Object> ref =
301        new WeakReference<Object>(
302            new Object() {
303              @Override
304              protected void finalize() {
305                finalizerRan.countDown();
306              }
307            });
308
309    await(finalizerRan);
310    awaitClear(ref);
311
312    // Hope to catch some stragglers queued up behind our finalizable object
313    System.runFinalization();
314  }
315
316  private static RuntimeException formatRuntimeException(String format, Object... args) {
317    return new RuntimeException(String.format(Locale.ROOT, format, args));
318  }
319}