JDK-6986416 : Warn of unprotected AutoCloseables in try-with-resources initializers
  • Type: Enhancement
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 7
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: generic
  • CPU: generic
  • Submitted: 2010-09-21
  • Updated: 2022-05-09
Related Reports
Relates :  
Relates :  
Description
As noted in a comment about try-with-resources
http://blogs.sun.com/darcy/entry/project_coin_updated_arm_spec#comment-1284742850000

"While it is true that the BufferedReader(Reader) constructor is very unlikely to throw an exception, there are many variations on this code in which failure to safely treat decorated resources could cause unacceptably common bugs. For example, a (misguided) attempt to match buffer size to file length:

File ini = new File("C:\\whatever.ini");
try (BufferedReader br = new BufferedReader(new FileReader(ini), (int) ini.length()) {
parse(br.readLine());
}

will throw an IllegalArgumentException but leave whatever.ini locked and unusable by other processes if it is of zero length!

Similarly, making an InputStreamReader with a charsetName could throw UnsupportedEncodingException, leaking the underlying InputStream. This could easily happen on a production JVM but never in testing, in case the list of supported encodings differs.

FindBugs could detect this class of mistake, of course, but I think developer documentation introducing the new syntax should be sure to emphasize that it is safest to declare an explicit variable for the most basic object which might possibly hold a native resource (e.g. FileReader), followed by any needed decorators.

I might even suggest a compiler "lint" warning in case an initializer expression in an ARM block contains a subexpression assignable to AutoCloseable."

Filing this rfe about the suggested lint warning.