java成员变量垃圾回收_JAVA 对象被垃圾回收后其成员变量可用吗? | 学步园

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

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);

}

}

下面为程序运行输出:

Has Buffer gone away?

first gc finished!

Has Buffer gone away?

Buffer gone away! //此时对象已被垃圾回收

abc //访问数据正常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值