JAVA 对象被垃圾回收后其成员变量可用吗?

来源:互联网 发布:沙丁鱼流量软件下载 编辑:程序博客网 时间:2024/04/28 22:55

  我们知道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;}@Overrideprotected void finalize() throws Throwable {System.out.println("Buffer gone away!");}}class HandleBuffer{byte[] buf = null;public HandleBuffer(byte[] buf){this.buf = buf;}@Overridepublic String toString() {return new String(buf);}}

下面为程序运行输出:

Has Buffer gone away?first gc finished!Has Buffer gone away?Buffer gone away!  //此时对象已被垃圾回收abc                //访问数据正常