This Java code will hold/occupy file descriptors after it runs. After using Reader, I should close it. (I once thought that using the .lines
approach would close the stream, actually it doesn`t close stream.)
private static String getContent(String filePath) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new ClassPathResource(filePath).getInputStream(), StandardCharsets.UTF_8));
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
}
Then I run this loop, try to run above code 20,000 times:
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 20000; i++) {
getContent("test.json"); // assume there is a file called test.json
}
Thread.sleep(10 * 60 * 1000l); // try to hold the execution
}
Next, I try to count the number of file descriptors the program holds by using the lsof
command.
// assume the process id (PID) is 12921
lsof -p 12921 | grep test.json | wc -l
Expected result:
20000
Actual result:
3932
Question
Why are there fewer file descriptors(3,932) than necessary(20,000)?
Is there some file descriptors being reused?
Any advice is appreciated, thanks in advance.