因为 Dalvik 的 FileInputStream 将 close itself when it is garbage collected(对于 OpenJDK/Oracle 也是如此),实际泄漏文件描述符的情况比您想象的要少。当然,文件描述符会在 GC 运行之前“泄露”,因此根据您的程序,可能需要一段时间才能回收它们。
要实现更持久的泄漏,您必须通过在内存中的某处保留对流的引用来防止流被垃圾收集。
这是一个简短的示例,它每 1 秒加载一个属性文件并跟踪它的每次更改:
public class StreamLeak {
/**
* A revision of the properties.
*/
public static class Revision {
final ZonedDateTime time = ZonedDateTime.now();
final PropertiesFile file;
Revision(PropertiesFile file) {
this.file = file;
}
}
/*
* Container for {@link Properties} that implements lazy loading.
*/
public static class PropertiesFile {
private final InputStream stream;
private Properties properties;
PropertiesFile(InputStream stream) {
this.stream = stream;
}
Properties getProperties() {
if(this.properties == null) {
properties = new Properties();
try {
properties.load(stream);
} catch(IOException e) {
e.printStackTrace();
}
}
return properties;
}
@Override
public boolean equals(Object o) {
if(o instanceof PropertiesFile) {
return ((PropertiesFile)o).getProperties().equals(getProperties());
}
return false;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
URL url = new URL(args[0]);
LinkedList<Revision> revisions = new LinkedList<>();
// Loop indefinitely
while(true) {
// Load the file
PropertiesFile pf = new PropertiesFile(url.openStream());
// See if the file has changed
if(revisions.isEmpty() || !revisions.getLast().file.equals(pf)) {
// Store the new revision
revisions.add(new Revision(pf));
System.out.println(url.toString() + " has changed, total revisions: " + revisions.size());
}
Thread.sleep(1000);
}
}
}
由于延迟加载,我们将 InputStream 保留在 PropertiesFile 中,每当我们创建新的 Revision 时都会保留它,因为我们从来没有关闭我们将在此处泄漏文件描述符的流。
现在,当程序终止时,这些打开的文件描述符将被操作系统关闭,但只要程序正在运行,它就会继续泄漏文件描述符,这可以通过使用lsof 看到:
$ lsof | grep pf.properties | head -n 3
java 6938 raniz 48r REG 252,0 0 262694 /tmp/pf.properties
java 6938 raniz 49r REG 252,0 0 262694 /tmp/pf.properties
java 6938 raniz 50r REG 252,0 0 262694 /tmp/pf.properties
$ lsof | grep pf.properties | wc -l
431
如果我们强制 GC 运行,我们可以看到大部分都返回了:
$ jcmd 6938 GC.run
6938:
Command executed successfully
$ lsof | grep pf.properties | wc -l
2
剩下的两个描述符是存储在Revisions中的。
我在我的 Ubuntu 机器上运行它,但如果在 Android 上运行,输出看起来会相似。