Will this method cause a memory leak when it throws an exception?
public static void warnUser(String name) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(dir + "warnings.txt", true));
writer.newLine();
writer.write(name);
writer.close();
} catch (Exception e) {
System.out.println(e.getMessage());
System.err.println("error giving warning to: " + name);
}
}
Is this better?
public static void warnUser(String name) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(dir + "warnings.txt", true))) {
writer.newLine();
writer.write(name);
} catch (Exception e) {
System.out.println(e.getMessage());
System.err.println("error giving warning to: " + name);
}
}
A memory leak? No, once execution leaves this method, be it through return or throwing an exception, the BufferedWriter object will no longer be reachable, and becomes eligible for garbage collection.
However, as you are not invoking the close method when an exception is thrown while writing to the file, the file will remain open, preventing anybody from using it, and possibly exhausting the limited number of files that the operating system can keep open at any given time, until finally the garbage collector gets around to collecting the object, which will trigger its finalizer which closes the file, but you don't know when that is (it can easily take hours if you're unlucky). This is why operating system resources such as files should be closed right when your program no longer needs them. That's why InputStreams have a close method, and Java has a try-with-resources statement.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments