7015589: (spec) BufferedWriter.close leaves stream open if close of underlying Writer fails

Alan Bateman Alan.Bateman at oracle.com
Tue Aug 9 11:43:14 UTC 2011


A few months back there was a bug report [1] pointing out that it's 
possible to continue writing to a BufferedWriter after invoking its 
close method and the close fails. A similar issue arises with 
BufferedOutputStream and other classes. At issue is whether a stream (or 
more generally a resource) is considered closed in the event that the 
close method fails. This isn't something that Closeable is clear on. Joe 
tells me that this didn't come up in the Coin discussions on 
try-with-resources either.

I think it's safe to say that it would be desirable that close releases 
the resources for failing cases as otherwise the resources may never be 
released (esp. with try-with-resources usages). Furthermore, when there 
are multiple resources involved, or cases like the bug report where one 
stream wraps another, then it would be desirable to keep the state of 
the resources in sync. To that end, the changes here propose adding an 
advisory note to AutoCloseable to advise implementers to release the 
underlying resources and to mark the resource as closed prior to 
throwing the exception.

For the specific buffering classes discussed at the time, these are 
changed to follow this advise (but their javadoc isn't changed as there 
may be other implementations or these classes extended in many ways). In 
the case of BufferedWriter it is also fixed so that any exception from 
flushing the underlying writer isn't supplanted by the exception from 
close. In the case of FilterOutputStream (BufferedOutputStream extends 
it) then it is fixed so that it doesn't ignore the exception thrown when 
flushing the underlying stream. This is clearly the right thing to do 
but it does mean that close can now throw an IOException for a case 
where it didn't before. For now I don't propose to include a 
compatibility switch but this may be something that has to revisited 
later. There are other classes in java.io that could also be cleaned up 
but I don't propose to do a complete audit at this time.

The webrev with the changes is here:
   http://cr.openjdk.java.net/~alanb/7015589/webrev/

Thanks,
Alan.

[1] 
http://mail.openjdk.java.net/pipermail/core-libs-dev/2011-January/005732.html



More information about the core-libs-dev mailing list