Skip to content

Instantly share code, notes, and snippets.

@danielshaya
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielshaya/f6c3d90c55b8298264d3 to your computer and use it in GitHub Desktop.
Save danielshaya/f6c3d90c55b8298264d3 to your computer and use it in GitHub Desktop.
Test to show what happens if you don't close Files.lines()
package utility;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.stream.Stream;
public class Test2 {
public static void main(String[] args) throws IOException{
int times = 100_000;
Path path = Paths.get("/tmp", "date.txt");
Test2 t2 = new Test2();
t2.setDate(path);
for (int i = 0; i < times; i++) {
t2.run1(path);
}
for (int i = 0; i < times; i++) {
t2.run2(path);
}
for (int i = 0; i < times; i++) {
t2.run3(path); //throws exception too many files open
}
System.out.println("finished");
}
public String run1(Path path){
try(BufferedReader br = new BufferedReader(new FileReader(path.toFile()))){
return br.readLine();
} catch (IOException e) {
throw new AssertionError(e);
}
}
public String run2(Path path){
try(Stream<String> stream = Files.lines(path)) {
return stream.findFirst().get();
} catch (IOException e) {
throw new AssertionError(e);
}
}
public String run3(Path path) throws IOException{
return Files.lines(path).findFirst().get();
}
public void setDate(Path path) {
try (FileWriter writer = new FileWriter(path.toFile())){
writer.write(new Date().toString());
writer.flush();
} catch (IOException e) {
throw new AssertionError(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment