-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeakReferenceExample.java
More file actions
46 lines (34 loc) · 949 Bytes
/
WeakReferenceExample.java
File metadata and controls
46 lines (34 loc) · 949 Bytes
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
/**
*
*/
package com.ankit.gcexamples;
import java.lang.ref.WeakReference;
/**
* @author ankitkumar
*
*/
public class WeakReferenceExample {
/**
* @param args
*/
public static void main(String[] args) {
Person p=new Person();
System.out.println("Original Person.."+p);
WeakReference<Person> wr=new WeakReference<Person>(p);
Person p1=wr.get();
System.out.println("Original Person thru WeakReference..."+p1);
p=null;
p1=null;
//even if original strong ref is set to null u can get it
//thru WeakRefernce until its garbage collected.
Person p2=wr.get();
System.out.println("Original Person thru WeakReference even original is set to null..."+p2);
//it can invoke gc based on JVM implementation
System.gc();
//it should be null if GC has claimed it as it has no Strong ref.
Person p3=wr.get();
System.out.println("Original Person after garbage collected.."+p3);
}
}
class Person{
}