我是靠谱客的博主 耍酷犀牛,这篇文章主要介绍JAVA 对象被垃圾回收后其成员变量可用吗?,现在分享给大家,希望可以做个参考。

  我们知道JVM中一个对象实例超出作用域或无引用的时候会被垃圾回收,那么他被垃圾回收后,依赖其成员变量的其他实例是否还能正常使用呢?经过测试后发现即使一个实例被垃圾回收,如果他内部的数据被其他对象使用,是不受影响的,下面看这个示例

复制代码
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
package test; public class mytest { public static void main(String[] args) throws Exception { HandleBuffer hb = null; { Buffer buf = new Buffer(); hb = new HandleBuffer(buf.getBuf()); buf = null; } System.out.println("Has Buffer gone away?"); System.in.read(); Runtime.getRuntime().gc(); System.out.println("first gc finished!"); System.in.read(); System.out.println("Has Buffer gone away?"); Thread.currentThread().sleep(1000); System.out.println(hb); System.in.read(); } } class Buffer{ private byte[] buf = new byte[1024]; public Buffer(){ this.buf = "abc".getBytes(); } public byte[] getBuf(){ return this.buf; } @Override protected void finalize() throws Throwable { System.out.println("Buffer gone away!"); } } class HandleBuffer{ byte[] buf = null; public HandleBuffer(byte[] buf){ this.buf = buf; } @Override public String toString() { return new String(buf); } }

下面为程序运行输出:

复制代码
1
2
3
4
5
6
7
Has Buffer gone away? first gc finished! Has Buffer gone away? Buffer gone away! //此时对象已被垃圾回收 abc //访问数据正常



 

 

最后

以上就是耍酷犀牛最近收集整理的关于JAVA 对象被垃圾回收后其成员变量可用吗?的全部内容,更多相关JAVA内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(78)

评论列表共有 0 条评论

立即
投稿
返回
顶部