Search code examples
javatry-with-resources

Behaviour of try-with-resources with closable parameters


Does Java-7's try-with-resources require the closable to be assigned directly to a variable? In short, is this block of code...

    try (final ObjectInputStream ois = new ObjectInputStream(
            new ByteArrayInputStream(data))) {
        return ois.readObject();
    }

Equivalent to this block?...

    try (final ByteArrayInputStream in = new ByteArrayInputStream(data);
         final ObjectInputStream ois = new ObjectInputStream(in)) {
        return ois.readObject();
    }

My understanding of Section 14.20.3 of the Java Language Specification says they are not the same and the resources must be assigned. This would be surprising from a common usage standpoint and I can't find any documentation warning against the pattern.


Solution

  • The two blocks are not equivalent in the sense that they won't generate the same code. But since ObjectInputStream.close() will call close() on the ByteArrayInputStream that you passed it, the first block is completely fine.

    EDIT: Something I forgot is that unlike reasonable constructions like new BufferedInputStream(new *InputStream(...)), the ObjectInputStream constructor actually reads from the stream you pass it and thus could reasonably throw an exception. For that reason I'd actually recommend the second block, not the first block.