In the new Try-wi开发者_StackOverflow中文版th-Resources syntax in Java 7 do I need to worry about the order of the resources?
try (InputStream in = loadInput(...); // <--- can these be in any order?
OutputStream out = createOutput(...) ){
copy(in, out);
}
catch (Exception e) {
// Problem reading and writing streams.
// Or problem opening one of them.
// If compound error closing streams occurs, it will be recorded on this exception
// as a "suppressedException".
}
Order matters if and only if it would matter when using the normal try {create resources} finally {close resources} syntax. Resources which were acquired first will be closed last. See the technotes for details.
In your example, the order definitely doesn't matter. You only use resources in the try block, where both are already available. If you would be connecting to the database, order or opening matters, but I would create a separate method to cover that. This method needs to implement AutoClosable and override the method close(). Although close() throws an Exception, your method doesn't have to.
Actually order doesn't matter at all. Ideally if the resources are un-related, you can open them in any order and they can be closed in any order.
If resources are related, you HAVE to follow the order to create them, for example first create Connection and then PreparedStatement, I don't have any proof but I think java closes resources in FIFO order to avoid any dependencies issue.
It matters if the opening of a resource depends on another resource being opened. For example, if the opening of B requires A being opened, you would obvious want A opened first. The other thing to attention is that resources are closed in the opposite order they are opened. For example, if you open A and then B, then when try-with-resources closes them, B is closed first followed by A.
精彩评论