2

Is there any difference between the two below code snippets, in terms of GC, resource closing etc?

or both are same/correct technically?

#Option 1
try(Writer writer = new OutputStreamWriter(new FileOutputStream(new File(path)), StandardCharsets.UTF_8)) {

}

#Option 2
try(FileOutputStream fis = new FileOutputStream(new File(path);
    Writer writer = new OutputStreamWriter(fis, StandardCharsets.UTF_8)) {

}

Just to understand what's the best approach to use in a highly used java application.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Shan
  • 57
  • 1
  • 6
  • 1
    No difference, tried resources get closed and cleaned up. I'd go for option 2 for better readability. – Robert Feb 10 '23 at 15:36
  • 1
    @Robert it is not correct. In the first example, if the outer constructor (`new OutputStreamWriter(...)`) failed, then internal object (`FileOutputStream`) remains unclosed and leaks resources – AterLux Feb 10 '23 at 15:39
  • @AterLux Although true in theory, it is extremely unlikely that `OutputStreamWriter(OutputStream, Charset)` throws an exception (basically the only option is to pass in a null for either parameter). – Mark Rotteveel Feb 10 '23 at 15:43
  • @MarkRotteveel in this specific usage it is indeed unlikely that OutputStreamWriter will throw, but in a more general case, `try(Writer writer = new OutputStreamWriter(new FileOutputStream(new File(path)), "bad charset name"))` _will_ leave the FileOutputStream open. – k314159 Feb 10 '23 at 15:47
  • @k314159 True, but unless you use user input for the character set, or run on a JVM with a limited number of character sets, that is a minor problem compared to the fact that you programmed in a non-existent character set. The stream will get closed eventually by its cleaner (or finalizer in older versions). – Mark Rotteveel Feb 10 '23 at 15:54

0 Answers0