Long l1 = new Long(1);
Long l2 = new Long(2);
Long l3 = new Long(3);
Long l4 = new Long(4);
WeakIdentityHashMap map = new WeakIdentityHashMap();
map.put(a, l1);
map.put(b, l2);
map.put(c, l3);
map.put(d, l4);
assertEquals(4, map.size());
System.gc();
assertEquals(4, map.size());
assertEquals(l1, map.get(a));
assertEquals(l2, map.get(b));
assertEquals(l3, map.get(c));
assertEquals(l4, map.get(d));
c = null;
d = null;
System.gc();
// try to garbage collect c and d 31 times at most
for (int j = 0; j < 30 && !(cCollected.value && dCollected.value); j++) {
for (int i = 0; i < 10000; i++)
{
String string = new String("any string to fill memory space...");
}
System.gc();
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
throw new RuntimeException("Unexpected exception, e");
}
}
assertEquals(2, map.size());
assertEquals(l1, map.get(a));
assertEquals(l2, map.get(b));
System.out.println("*** testWeakIdentityHashMap() - successful");
}