test case when one object is still referenced
@@ -29,6 +29,30 @@ public class WeakHashMapTest {
await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty);
}
+ @Test
+ public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() {
+ //given
+ WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
+ BigImage bigImageFirst = new BigImage("foo");
+ UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image");
+
+ BigImage bigImageSecond = new BigImage("foo_2");
+ UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2");
+
+ map.put(imageNameFirst, bigImageFirst);
+ map.put(imageNameSecond, bigImageSecond);
+ assertTrue(map.containsKey(imageNameFirst));
+ assertTrue(map.containsKey(imageNameSecond));
+
+ //when
+ imageNameFirst = null;
+ System.gc();
+
+ //then
+ await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1);
+ await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond));
+ }
+
class BigImage {
public final String imageId;
