Code Review 7000511: PrintStream, PrintWriter, Formatter leave files open when exception thrown

Alan Bateman Alan.Bateman at oracle.com
Tue Dec 14 18:03:48 UTC 2010


Chris Hegarty wrote:
> Failing java.io.PrintStream, java.io.PrintWriter, java.util.Scanner, 
> and java.util.Formatter multi-arg constructors that take a 
> java.io.File or String filename (as well as one or more additional 
> args) opens a FileIn/OutputStream to the given File/filename. If one 
> of the other given args causes the constructor to fail ( null or 
> unsupported charset for example ) the FileIn/OutputStream is never 
> closed, and the application does not have a reference to it. You rely 
> on the finalizer to close the stream.
>
> This is most serious on Windows because you cannot remove a file if 
> there is an open handle to it.
>
> I also cleaned up an existing regression test that fails in samevm 
> mode (partly) because of this. And removed another excluded test from 
> the list since its bug was fixed some time ago.
>
> Webrev:
>   http://cr.openjdk.java.net/~chegar/7000511/webrev.00/webrev/
>
> -Chris.
It would be good to get this one fixed. If I understand the proposal 
correctly, there may still be side effects when NPE or 
UnsupportedEncodingException is thrown. When I say "side effects" I mean 
that an empty file may be created or an existing file truncated before 
the exception is thrown. I wonder you've tried to extend the list of 
parameters to the private constructors to avoid this. A 
toCharset(String) method should be used to lookup the Charset for 
example rather than having OutputStreamWriter to do it.

One minor comment is that I see that PrintStream is using 
java.util.Objects. Nice to see it being used but I wonder about loading 
yet another class during startup (System.out and err are PrintStreams 
and are initialized early in the startup).

-Alan



More information about the core-libs-dev mailing list