Skip to content

Closables.closeQuietly should be deprecated or at least needs lots of warnings in documentation. #1118

Description

@gissuebot

Original issue created by reinierz on 2012-08-23 at 06:00 PM


About 95% of all the usage of closeQuietly I see is broken; closeQuietly's primary purpose right now appears to entice people to write buggy programs. That's not a good thing.

Some explanation is probably warranted. The vast majority of closables fall into two categories:

A) A readable; InputStream or Reader. The vast majority of implementations of any such streams never actually throw IOException, so the close(readable, true) method does nothing of any use whatsoever. closeQuietly lets you dodge the need to formally handle the wont-actually-ever-happen IOException, but this is rarely needed as the close method is usually near the read methods, which can and do throw IOException. Just pop the close() call into the try block and voila.

B) A writable; OutputStream or Writer. swallowing IOExceptions on close is very very very VERY bad, and something that the mere existence of closeQuietly is strongly enforcing. Many implementations use buffers, and if not the implementation itself, upstream systems might be buffering. No byte or character that was supplied to a 'write' method, even if that call to write did not cause an exception, is guaranteed to have gone anywhere until you flush the stream, which close implicitly does. Therefore, any exception that falls out of a close() method should be treated as if any number of previous write calls would have failed with that exception if only there were less buffers in between. In other words, there is no practical difference between write() throwing an exception and close() throwing an exception, for writables. closeQuietly() is an outright bug if used in this way, as it leads to programs silently ignoring a disk failure or network failure event. There is zero difference between silently ignoring IOExceptions thrown by your write() methods, and silently ignoring IOExceptions thrown by closing that stream or writer.

In conclusion, Closables.closeQuietly has vanishingly small true use cases, but in practice it is abused. Therefore, it should probably be removed (well, @Deprecated), or at least a lot of scary warnings need to be added to the javadoc to explain what it is for (to dodge the need to formally handle IOExceptions for readables, ONLY - it is inappropriate for anything else).

Closables.close does have a realistic use case (to facilitate the throwing of the first exception, and not the 'followup' usually less useful exception thrown by the close method once a write/read has already failed).

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions