• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.testing;
18 
19 import static java.util.concurrent.TimeUnit.SECONDS;
20 
21 import com.google.common.annotations.Beta;
22 import com.google.common.annotations.GwtIncompatible;
23 import com.google.errorprone.annotations.DoNotMock;
24 import com.google.j2objc.annotations.J2ObjCIncompatible;
25 import java.lang.ref.WeakReference;
26 import java.util.Locale;
27 import java.util.concurrent.CancellationException;
28 import java.util.concurrent.CountDownLatch;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.Future;
31 import java.util.concurrent.TimeoutException;
32 
33 /**
34  * Testing utilities relating to garbage collection finalization.
35  *
36  * <p>Use this class to test code triggered by <em>finalization</em>, that is, one of the following
37  * actions taken by the java garbage collection system:
38  *
39  * <ul>
40  *   <li>invoking the {@code finalize} methods of unreachable objects
41  *   <li>clearing weak references to unreachable referents
42  *   <li>enqueuing weak references to unreachable referents in their reference queue
43  * </ul>
44  *
45  * <p>This class uses (possibly repeated) invocations of {@link java.lang.System#gc()} to cause
46  * finalization to happen. However, a call to {@code System.gc()} is specified to be no more than a
47  * hint, so this technique may fail at the whim of the JDK implementation, for example if a user
48  * specified the JVM flag {@code -XX:+DisableExplicitGC}. But in practice, it works very well for
49  * ordinary tests.
50  *
51  * <p>Failure of the expected event to occur within an implementation-defined "reasonable" time
52  * period or an interrupt while waiting for the expected event will result in a {@link
53  * RuntimeException}.
54  *
55  * <p>Here's an example that tests a {@code finalize} method:
56  *
57  * <pre>{@code
58  * final CountDownLatch latch = new CountDownLatch(1);
59  * Object x = new MyClass() {
60  *   ...
61  *   protected void finalize() { latch.countDown(); ... }
62  * };
63  * x = null;  // Hint to the JIT that x is stack-unreachable
64  * GcFinalization.await(latch);
65  * }</pre>
66  *
67  * <p>Here's an example that uses a user-defined finalization predicate:
68  *
69  * <pre>{@code
70  * final WeakHashMap<Object, Object> map = new WeakHashMap<>();
71  * map.put(new Object(), Boolean.TRUE);
72  * GcFinalization.awaitDone(new FinalizationPredicate() {
73  *   public boolean isDone() {
74  *     return map.isEmpty();
75  *   }
76  * });
77  * }</pre>
78  *
79  * <p>Even if your non-test code does not use finalization, you can use this class to test for
80  * leaks, by ensuring that objects are no longer strongly referenced:
81  *
82  * <pre>{@code
83  * // Helper function keeps victim stack-unreachable.
84  * private WeakReference<Foo> fooWeakRef() {
85  *   Foo x = ....;
86  *   WeakReference<Foo> weakRef = new WeakReference<>(x);
87  *   // ... use x ...
88  *   x = null;  // Hint to the JIT that x is stack-unreachable
89  *   return weakRef;
90  * }
91  * public void testFooLeak() {
92  *   GcFinalization.awaitClear(fooWeakRef());
93  * }
94  * }</pre>
95  *
96  * <p>This class cannot currently be used to test soft references, since this class does not try to
97  * create the memory pressure required to cause soft references to be cleared.
98  *
99  * <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
109 public final class GcFinalization {
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    */
timeoutSeconds()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    */
awaitDone(Future<?> future)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    */
awaitDone(FinalizationPredicate predicate)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    */
await(CountDownLatch latch)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    */
createUnreachableLatchFinalizer(final CountDownLatch latch)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 {
isDone()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    */
awaitClear(final WeakReference<?> ref)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    */
awaitFullGc()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 
formatRuntimeException(String format, Object... args)316   private static RuntimeException formatRuntimeException(String format, Object... args) {
317     return new RuntimeException(String.format(Locale.ROOT, format, args));
318   }
319 }
320