Skip to content

Instantly share code, notes, and snippets.

@mathieuancelin
Last active December 10, 2015 19:48
Show Gist options
  • Save mathieuancelin/4483955 to your computer and use it in GitHub Desktop.
Save mathieuancelin/4483955 to your computer and use it in GitHub Desktop.
import org.junit.Assert;
import java.lang.ref.WeakReference;
public class MemoryLeakChecker<T> {
private static final int MAXGC = 50;
private final WeakReference<T> reference;
private final int calls;
public MemoryLeakChecker(T object) {
this.reference = new WeakReference<T>(object);
this.calls = MAXGC;
}
public MemoryLeakChecker(T object, int maxGCCalls) {
this.reference = new WeakReference<T>(object);
this.calls = maxGCCalls;
}
public T get() {
return reference.get();
}
public boolean isObjectGarbageCollected() {
return reference.get() == null;
}
public int getMaxGCCalls() {
return calls;
}
public void assertObjectIsGarbageCollected() {
Runtime runtime = Runtime.getRuntime();
for (int i = 0; i < calls; i++) {
runtime.runFinalization();
runtime.gc();
if (get() == null) { break; }
try { Thread.sleep(200); } catch (InterruptedException e) {}
}
Assert.assertNull("After " + calls + " Garbage collection, object isn't garbage collected yet :'(", get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment