Java 代码
1.Object o=new Object();
2.Object o1=o;
|
Java 代码
1.o=null;
2.o1=null;
|
Java 代码
1.String abc=new String("abc"); //1
2.SoftReference
3.WeakReference
4.abc=null; //4
5.abcSoftRef.clear();//5
|
Java 代码
Reference(T paramT, ReferenceQueue super T>paramReferenceQueue)
|
A obj = new A();
SoftRefenrence sr = new SoftReference(obj);
引用 时
if(sr!=null){
obj = sr.get();
}else{
obj = new A();
sr = new SoftReference(obj);
}
|
Java 代码
1.String abc=new String("abc");
2.WeakReference
3.abc=null;
4.System.out.println("before gc: "+abcWeakRef.get());
5.System.gc();
6.System.out.println("after gc: "+abcWeakRef.get());
|
A obj = new A();
WeakReference wr = new WeakReference(obj);
obj = null;
// 等待一段 时间, obj 对象就会被垃圾回收
...
if (wr.get()==null) {
System.out.println("obj 已 经被清除了 ");
} else {
System.out.println("obj 尚未被清除,其信息是 "+obj.toString());
}
...
}
|
Java 代码
1.import java.lang.ref.PhantomReference;
2.import java.lang.ref.Reference;
3.import java.lang.ref.ReferenceQueue;
4.import java.lang.reflect.Field;
5.
6.public class Test {
7. public static boolean isRun = true;
8.
9. public static void main(String[] args) throws Exception {
10. String abc = new String("abc");
11. System.out.println(abc.getClass() + "@" + abc.hashCode());
12. final ReferenceQueue referenceQueue = new ReferenceQueue
13. new Thread() {
14. public void run() {
15. while (isRun) {
16. Object o = referenceQueue.poll();
17. if (o != null) {
18. try {
19. Field rereferent = Reference.class
20. .getDeclaredField("referent");
21. rereferent.setAccessible(true);
22. Object result = rereferent.get(o);
23. System.out.println("gc will collect:"
24. + result.getClass() + "@"
25. + result.hashCode());
26. } catch (Exception e) {
27.
28. e.printStackTrace();
29. }
30. }
31. }
32. }
33. }.start();
34. PhantomReference
35. referenceQueue);
36. abc = null;
37. Thread.currentThread().sleep(3000);
38. System.gc();
39. Thread.currentThread().sleep(3000);
40. isRun = false;
41. }
42.
43.}
|