我的java代码似乎有句柄泄漏,哪个调试工具适合检查?
答案 0 :(得分:2)
lsof命令将列出与该程序关联的所有文件。
答案 1 :(得分:1)
由于没有给出任何例子,我正在添加我的
package org.gradle;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class FileDescriptorDemoOne {
static int index_count;
public static void main(String[] args) throws IOException {
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
public void run() {
index_count++;
// do stuff
File file = new File("/tmp/helloworld.txt");
FileDescriptor fd;
FileOutputStream fos1;
try {
fos1 = new FileOutputStream(file);
fd = fos1.getFD();
//passing FileDescriptor to another FileOutputStream
FileOutputStream fos2 = new FileOutputStream(fd);
fos2.write(index_count++);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 5, TimeUnit.SECONDS);
}
}
显然,上面的代码会每隔几秒就泄漏文件描述符。
要抓住这个用途
lsof | grep helloworld
java 6015 vic 8w REG 1,4 12 86076888 /private/tmp/helloworld.txt
java 6015 vic 9w REG 1,4 12 86076888 /private/tmp/helloworld.txt
java 6015 vic 10w REG 1,4 12 86076888 /private/tmp/helloworld.txt