• 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.GwtIncompatible;
22 import com.google.common.annotations.J2ktIncompatible;
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 @GwtIncompatible
107 @J2ktIncompatible
108 @J2ObjCIncompatible // gc
109 @ElementTypesAreNonnullByDefault
110 public final class GcFinalization {
GcFinalization()111   private GcFinalization() {}
112 
113   /**
114    * 10 seconds ought to be long enough for any object to be GC'ed and finalized. Unless we have a
115    * gigantic heap, in which case we scale by heap size.
116    */
timeoutSeconds()117   private static long timeoutSeconds() {
118     // This class can make no hard guarantees.  The methods in this class are inherently flaky, but
119     // we try hard to make them robust in practice.  We could additionally try to add in a system
120     // load timeout multiplier.  Or we could try to use a CPU time bound instead of wall clock time
121     // bound.  But these ideas are harder to implement.  We do not try to detect or handle a
122     // user-specified -XX:+DisableExplicitGC.
123     //
124     // TODO(user): Consider using
125     // java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage()
126     //
127     // TODO(user): Consider scaling by number of mutator threads,
128     // e.g. using Thread#activeCount()
129     return Math.max(10L, Runtime.getRuntime().totalMemory() / (32L * 1024L * 1024L));
130   }
131 
132   /**
133    * Waits until the given future {@linkplain Future#isDone is done}, invoking the garbage collector
134    * as necessary to try to ensure that this will happen.
135    *
136    * @throws RuntimeException if timed out or interrupted while waiting
137    */
awaitDone(Future<?> future)138   public static void awaitDone(Future<?> future) {
139     if (future.isDone()) {
140       return;
141     }
142     long timeoutSeconds = timeoutSeconds();
143     long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds);
144     do {
145       System.runFinalization();
146       if (future.isDone()) {
147         return;
148       }
149       System.gc();
150       try {
151         future.get(1L, SECONDS);
152         return;
153       } catch (CancellationException | ExecutionException ok) {
154         return;
155       } catch (InterruptedException ie) {
156         throw new RuntimeException("Unexpected interrupt while waiting for future", ie);
157       } catch (TimeoutException tryHarder) {
158         /* OK */
159       }
160     } while (System.nanoTime() - deadline < 0);
161     throw formatRuntimeException("Future not done within %d second timeout", timeoutSeconds);
162   }
163 
164   /**
165    * Waits until the given predicate returns true, invoking the garbage collector as necessary to
166    * try to ensure that this will happen.
167    *
168    * @throws RuntimeException if timed out or interrupted while waiting
169    */
awaitDone(FinalizationPredicate predicate)170   public static void awaitDone(FinalizationPredicate predicate) {
171     if (predicate.isDone()) {
172       return;
173     }
174     long timeoutSeconds = timeoutSeconds();
175     long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds);
176     do {
177       System.runFinalization();
178       if (predicate.isDone()) {
179         return;
180       }
181       CountDownLatch done = new CountDownLatch(1);
182       createUnreachableLatchFinalizer(done);
183       await(done);
184       if (predicate.isDone()) {
185         return;
186       }
187     } while (System.nanoTime() - deadline < 0);
188     throw formatRuntimeException(
189         "Predicate did not become true within %d second timeout", timeoutSeconds);
190   }
191 
192   /**
193    * Waits until the given latch has {@linkplain CountDownLatch#countDown counted down} to zero,
194    * invoking the garbage collector as necessary to try to ensure that this will happen.
195    *
196    * @throws RuntimeException if timed out or interrupted while waiting
197    */
await(CountDownLatch latch)198   public static void await(CountDownLatch latch) {
199     if (latch.getCount() == 0) {
200       return;
201     }
202     long timeoutSeconds = timeoutSeconds();
203     long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds);
204     do {
205       System.runFinalization();
206       if (latch.getCount() == 0) {
207         return;
208       }
209       System.gc();
210       try {
211         if (latch.await(1L, SECONDS)) {
212           return;
213         }
214       } catch (InterruptedException ie) {
215         throw new RuntimeException("Unexpected interrupt while waiting for latch", ie);
216       }
217     } while (System.nanoTime() - deadline < 0);
218     throw formatRuntimeException(
219         "Latch failed to count down within %d second timeout", timeoutSeconds);
220   }
221 
222   /**
223    * Creates a garbage object that counts down the latch in its finalizer. Sequestered into a
224    * separate method to make it somewhat more likely to be unreachable.
225    */
createUnreachableLatchFinalizer(CountDownLatch latch)226   private static void createUnreachableLatchFinalizer(CountDownLatch latch) {
227     Object unused =
228         new Object() {
229           @Override
230           protected void finalize() {
231             latch.countDown();
232           }
233         };
234   }
235 
236   /**
237    * A predicate that is expected to return true subsequent to <em>finalization</em>, that is, one
238    * of the following actions taken by the garbage collector when performing a full collection in
239    * response to {@link System#gc()}:
240    *
241    * <ul>
242    *   <li>invoking the {@code finalize} methods of unreachable objects
243    *   <li>clearing weak references to unreachable referents
244    *   <li>enqueuing weak references to unreachable referents in their reference queue
245    * </ul>
246    */
247   @DoNotMock("Implement with a lambda")
248   public interface FinalizationPredicate {
isDone()249     boolean isDone();
250   }
251 
252   /**
253    * Waits until the given weak reference is cleared, invoking the garbage collector as necessary to
254    * try to ensure that this will happen.
255    *
256    * <p>This is a convenience method, equivalent to:
257    *
258    * <pre>{@code
259    * awaitDone(new FinalizationPredicate() {
260    *   public boolean isDone() {
261    *     return ref.get() == null;
262    *   }
263    * });
264    * }</pre>
265    *
266    * @throws RuntimeException if timed out or interrupted while waiting
267    */
awaitClear(WeakReference<?> ref)268   public static void awaitClear(WeakReference<?> ref) {
269     awaitDone(
270         new FinalizationPredicate() {
271           @Override
272           public boolean isDone() {
273             return ref.get() == null;
274           }
275         });
276   }
277 
278   /**
279    * Tries to perform a "full" garbage collection cycle (including processing of weak references and
280    * invocation of finalize methods) and waits for it to complete. Ensures that at least one weak
281    * reference has been cleared and one {@code finalize} method has been run before this method
282    * returns. This method may be useful when testing the garbage collection mechanism itself, or
283    * inhibiting a spontaneous GC initiation in subsequent code.
284    *
285    * <p>In contrast, a plain call to {@link java.lang.System#gc()} does not ensure finalization
286    * processing and may run concurrently, for example, if the JVM flag {@code
287    * -XX:+ExplicitGCInvokesConcurrent} is used.
288    *
289    * <p>Whenever possible, it is preferable to test directly for some observable change resulting
290    * from GC, as with {@link #awaitClear}. Because there are no guarantees for the order of GC
291    * finalization processing, there may still be some unfinished work for the GC to do after this
292    * method returns.
293    *
294    * <p>This method does not create any memory pressure as would be required to cause soft
295    * references to be processed.
296    *
297    * @throws RuntimeException if timed out or interrupted while waiting
298    * @since 12.0
299    */
awaitFullGc()300   public static void awaitFullGc() {
301     CountDownLatch finalizerRan = new CountDownLatch(1);
302     WeakReference<Object> ref =
303         new WeakReference<>(
304             new Object() {
305               @Override
306               protected void finalize() {
307                 finalizerRan.countDown();
308               }
309             });
310 
311     await(finalizerRan);
312     awaitClear(ref);
313 
314     // Hope to catch some stragglers queued up behind our finalizable object
315     System.runFinalization();
316   }
317 
formatRuntimeException(String format, Object... args)318   private static RuntimeException formatRuntimeException(String format, Object... args) {
319     return new RuntimeException(String.format(Locale.ROOT, format, args));
320   }
321 }
322