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

Sign up
Appearance settings

Commit a75678d

Browse files
[A] 添加弱引用实例
1 parent 3021ea8 commit a75678d

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines 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)

AltStyle によって変換されたページ (->オリジナル) /