|
| 1 | +package com.baeldung.weakhashmap; |
| 2 | + |
| 3 | + |
| 4 | +import org.junit.Test; |
| 5 | + |
| 6 | +import java.util.WeakHashMap; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | + |
| 9 | +import static com.jayway.awaitility.Awaitility.await; |
| 10 | +import static org.junit.Assert.assertTrue; |
| 11 | + |
| 12 | +public class WeakHashMapTest { |
| 13 | + |
| 14 | + @Test |
| 15 | + public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() { |
| 16 | + //given |
| 17 | + WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>(); |
| 18 | + BigImage bigImage = new BigImage("image_id"); |
| 19 | + UniqueImageName imageName = new UniqueImageName("name_of_big_image"); |
| 20 | + |
| 21 | + map.put(imageName, bigImage); |
| 22 | + assertTrue(map.containsKey(imageName)); |
| 23 | + |
| 24 | + //when big image key is not reference anywhere |
| 25 | + imageName = null; |
| 26 | + System.gc(); |
| 27 | + |
| 28 | + //then GC will finally reclaim that object |
| 29 | + await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty); |
| 30 | + } |
| 31 | + |
| 32 | + @Test |
| 33 | + public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() { |
| 34 | + //given |
| 35 | + WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>(); |
| 36 | + BigImage bigImageFirst = new BigImage("foo"); |
| 37 | + UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image"); |
| 38 | + |
| 39 | + BigImage bigImageSecond = new BigImage("foo_2"); |
| 40 | + UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2"); |
| 41 | + |
| 42 | + map.put(imageNameFirst, bigImageFirst); |
| 43 | + map.put(imageNameSecond, bigImageSecond); |
| 44 | + assertTrue(map.containsKey(imageNameFirst)); |
| 45 | + assertTrue(map.containsKey(imageNameSecond)); |
| 46 | + |
| 47 | + //when |
| 48 | + imageNameFirst = null; |
| 49 | + System.gc(); |
| 50 | + |
| 51 | + //then |
| 52 | + await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1); |
| 53 | + await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond)); |
| 54 | + } |
| 55 | + |
| 56 | + |
| 57 | + class BigImage { |
| 58 | + public final String imageId; |
| 59 | + |
| 60 | + BigImage(String imageId) { |
| 61 | + this.imageId = imageId; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + class UniqueImageName { |
| 66 | + public final String imageName; |
| 67 | + |
| 68 | + UniqueImageName(String imageName) { |
| 69 | + this.imageName = imageName; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments