Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6986416

Warn of unprotected AutoCloseables in try-with-resources initializers

    XMLWordPrintable

Details

    • Enhancement
    • Resolution: Unresolved
    • P4
    • None
    • 7
    • tools
    • generic
    • generic

    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.

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              darcy Joe Darcy
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Imported:
                Indexed: