import java.util.*; public class MemoryLeak { public static double oneLevel(Map map, int n, Random r) { List keys = new ArrayList(n); for(int i = 0; i < n; i++) { int index = r.nextInt(); double value = r.nextDouble(); Key key = new Key(index); map.put(key,value); keys.add(key); } double total = 0.0; for(Key key: keys) { total += map.get(key); } return total; } public static void main(String[] args) { int levelSize = (args.length > 0) ? Integer.parseInt(args[0]) : 1000000; int randomSeed = (args.length > 1) ? Integer.parseInt(args[1]) : 0; Random r = new Random(randomSeed); // this version will run out of memory Map map = new HashMap(); // this version will run forever //Map map = new WeakHashMap(); for(int i = 0; ; i++) { double sum = oneLevel(map,levelSize,r); System.out.println("x " + i + " " + map.size() + " " + sum + " " + new Date()); } } } class Key { int value = 0; public Key(int n) { value = n;} public String toString() { return ""; } }