以下是程序代码:
import java.io.*;
import java.util.*;
public class GCTest {
public static void main(String[] args) throws Exception {
List cache = new ArrayList();
while (true) {
cache.add(new GCTest().run());
System.out.println("done");
}
}
private byte[] run() throws IOException {
Test test = new Test();
InputStream is = test.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[256];
int len = 0;
while (-1 != (len = is.read())) {
baos.write(buff, 0, len);
}
return baos.toByteArray();
}
private class Test {
private InputStream is;
public InputStream getInputStream() throws FileNotFoundException {
is = new FileInputStream("GCTest.class");
return is;
}
protected void finalize() throws IOException {
System.out.println("finalize");
is.close();
is = null;
}
}
}
你认为在run方法中的while循环仍在执行且本地变量test仍在作用域内时,finalize方法是否会被调用?
更重要的是,这种行为是否有定义?Sun有没有声明这是实现定义?
这与SO上以前提出的问题相反,人们主要关注内存泄漏。这里我们有GC积极清除我们仍然感兴趣的变量。你可能会认为,因为test仍然在“作用域”内,它不会被GC。
值得一提的是,根据JVM实现的不同,有时测试“有效”(即最终会出现OOM),有时会失败。
顺便说一句,我并不是在为这段代码辩护,这只是一个在工作中遇到的问题。