Last active
August 29, 2015 14:18
-
-
Save ChristinGorman/3a2a7ddae9230202a765 to your computer and use it in GitHub Desktop.
GC of lambdas in java 8
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 java.lang.ref.WeakReference; | |
import java.util.WeakHashMap; | |
public class Test { | |
/** | |
* Still don't know why the first two lambdas don't get cleared by the GC :( | |
*/ | |
public static void main(String[] args) throws Exception { | |
WeakHashMap<Runnable, Boolean> map = new WeakHashMap<>(); | |
//these two don't get cleared by the garbage collector | |
map.put(() -> System.out.println("lambda"), true); | |
map.put(() -> System.out.println("lambda"), true); | |
//this one does | |
int i = 10; | |
map.put(() -> System.out.println(i), true); | |
//so does this one | |
map.put(new Runnable() { | |
@Override | |
public void run() { | |
System.out.println("anonymous inner class"); | |
} | |
}, true); | |
int count = 0; | |
while (!map.isEmpty() && count++ < 6) { | |
System.gc(); | |
Thread.sleep(50); | |
} | |
//size should be 0 by now, but is 2 | |
System.out.println("size() : " + map.size()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment