Last active
December 10, 2015 19:48
-
-
Save mathieuancelin/4483955 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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