Skip to content

Instantly share code, notes, and snippets.

@timboudreau
Created August 15, 2019 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timboudreau/b05e2977ec268a0276427946b84370f0 to your computer and use it in GitHub Desktop.
Save timboudreau/b05e2977ec268a0276427946b84370f0 to your computer and use it in GitHub Desktop.
package com.mastfrog.lambda.gc;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class LambdaGCTest {
// This test will fail - member references are the same as
// creating a new WeakReference<Runnable>(new Whatever()) - it is
// instantly garbage collected
@Test
public void testSomeMethod() {
Touchable touchable = new Touchable();
Listener listener = new Listener(touchable);
for (int i = 0; i < 100; i++) {
touchable.touch();
listener.assertIncremented();
System.gc();
}
}
static class Touchable {
private final List<WeakReference<Runnable>> listeners
= new ArrayList<>(10);
void listen(Runnable listener) {
listeners.add(new WeakReference<>(listener));
}
void touch() {
for (Iterator<WeakReference<Runnable>> it = listeners.iterator(); it.hasNext();) {
WeakReference<Runnable> ref = it.next();
Runnable toRun = ref.get();
if (toRun == null) {
it.remove();
} else {
toRun.run();
}
}
}
}
static class Listener {
private int lastTouchCount;
private int touchCount;
Listener(Touchable touchable) {
touchable.listen(this::increment);
}
void increment() {
touchCount++;
}
void assertIncremented() {
assertTrue(touchCount > lastTouchCount, "Was not incremented");
lastTouchCount = touchCount;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment