-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWeakHashMapExample.java
52 lines (37 loc) · 1 KB
/
WeakHashMapExample.java
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
48
49
50
51
52
package com.ankit.gcexamples;
import java.util.Date;
import java.util.WeakHashMap;
public class WeakHashMapExample {
public static void main(String[] args) {
WeakHashMap<Person1, PersonMetaData> weakHashMap=new WeakHashMap<>();
//strong ref
Person1 ankit=new Person1();
//this key is weak reference
weakHashMap.put(ankit, new PersonMetaData());
PersonMetaData p=weakHashMap.get(ankit);
System.out.println(p);
//nulling strong ref
ankit=null;
//running gc so that person object is garbage collected
//and weak reference in weak hashmap should be removed as obj is gcd
System.gc();
//if gc has collected this obj map key and value also be removed.
if(weakHashMap.containsValue(p)){
System.out.println("still contains key");
}else{
System.out.println("key gone");
}
}
}
final class Person1{
}
class PersonMetaData{
Date date;
public PersonMetaData() {
date=new Date();
}
@Override
public String toString() {
return "PersonMetaData [date=" + date + "]";
}
}