File tree Expand file tree Collapse file tree
src/test/java/com/baeldung/weakhashmap Expand file tree Collapse file tree Original file line number Diff line number Diff line change 154154 <version >${mockito.version} </version >
155155 <scope >test</scope >
156156 </dependency >
157+ <dependency >
158+ <groupId >com.jayway.awaitility</groupId >
159+ <artifactId >awaitility</artifactId >
160+ <version >${avaitility.version} </version >
161+ <scope >test</scope >
162+ </dependency >
157163
158164 <dependency >
159165 <groupId >commons-codec</groupId >
371377 <mockito .version>1.10.19</mockito .version>
372378 <testng .version>6.10</testng .version>
373379 <assertj .version>3.6.1</assertj .version>
380+ <avaitility .version>1.7.0</avaitility .version>
374381
375382 <!-- maven plugins -->
376383 <maven-compiler-plugin .version>3.6.0</maven-compiler-plugin .version>
Original file line number Diff line number Diff line change 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+
33+ class BigImage {
34+ public final String imageId ;
35+
36+ BigImage (String imageId ) {
37+ this .imageId = imageId ;
38+ }
39+ }
40+
41+ class UniqueImageName {
42+ public final String imageName ;
43+
44+ UniqueImageName (String imageName ) {
45+ this .imageName = imageName ;
46+ }
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments