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