-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWeakHashMapDemo.java
More file actions
47 lines (38 loc) · 1.26 KB
/
WeakHashMapDemo.java
File metadata and controls
47 lines (38 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package learnCollections;
import java.util.Map;
import java.util.WeakHashMap;
// string literals inside string pool are strong referenced throughout the life-cycle of program
public class WeakHashMapDemo {
public static void main(String[] args) {
WeakHashMap<String, Image> imageCache = new WeakHashMap<>();
loadCache(imageCache);
System.out.println(imageCache); // {img1=Image 1, img2=Image 2}
System.gc();
simulateApplicationRunning();
System.out.println("Cache after running (some entries may be cleared): " + imageCache); // {}
}
public static void loadCache(Map<String, Image> imageCache) {
String k1 = new String("img1");
String k2 = new String("img2");
imageCache.put(k1, new Image("Image 1"));
imageCache.put(k2, new Image("Image 2"));
}
private static void simulateApplicationRunning() {
try {
System.out.println("Simulating application running...");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Image {
private String name;
public Image(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}