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.GwtIncompatible; 022import com.google.common.annotations.J2ktIncompatible; 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@GwtIncompatible 107@J2ktIncompatible 108@J2ObjCIncompatible // gc 109@ElementTypesAreNonnullByDefault 110public final class 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 */ 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 */ 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 */ 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 */ 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 */ 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 { 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 */ 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 */ 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 318 private static RuntimeException formatRuntimeException(String format, Object... args) { 319 return new RuntimeException(String.format(Locale.ROOT, format, args)); 320 } 321}