Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit a75678d

Browse filesBrowse files
committed
[A] 添加弱引用实例
1 parent 3021ea8 commit a75678d
Copy full SHA for a75678d

File tree

Expand file treeCollapse file tree

1 file changed

+34
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+34
-0
lines changed
Open diff view settings
Collapse file
+34Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.learnjava.reference;
2+
3+
import java.lang.ref.Reference;
4+
import java.lang.ref.ReferenceQueue;
5+
import java.lang.ref.WeakReference;
6+
7+
public class WeakReferenceTest {
8+
public static void main(String[] args) throws Exception {
9+
test02();
10+
}
11+
12+
private static void test02() throws InterruptedException {
13+
ReferenceQueue refQueue = new ReferenceQueue();
14+
15+
// 10 mb
16+
byte[] buffer = new byte[1024 * 1024 * 10];
17+
WeakReference weakReference = new WeakReference(buffer, refQueue);
18+
// 失去强引用关联
19+
buffer = null;
20+
21+
Reference ref0 = refQueue.poll();
22+
System.out.println("gc 执行之前, refQueue中是否有数据?" + (ref0 != null ? "有" : "没有"));
23+
System.out.println("gc 执行之前, ref引用的对象:" + weakReference.get());
24+
25+
System.gc();
26+
// 确保gc程序执行
27+
Thread.sleep(1000);
28+
29+
System.out.println("gc 执行之前, ref引用的对象:" + weakReference.get());
30+
31+
Reference ref = refQueue.poll();
32+
System.out.println("referenceQueue 中获取的 ref与 weakReference中的是否一致?" + (ref == weakReference));
33+
}
34+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.