Reputation: 12837
What are the precedence rules for try-with-resource
construct? Here is an example (note: all the mentioned classes implement Closeable
):
try (Page closeablePage = page;
PipedOutputStream out = outs;
SequenceWriter sequenceWriter = mapper.writer().writeValuesAsArray(out)) {
// do stuff
} finally {
callback.run();
}
When is the callback run? My assumptions is:
SequenceWriter
PipedOutputStream
Page
Am I wrong here?
Upvotes: 5
Views: 1569
Reputation: 137084
The finally
block will be run after all resources have been closed by the try-with-resources
statement.
This is specified in the JLS section 14.20.3.2, quoting:
Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.
Additionally, all resources are closed in reverse declaration order. Quoting section 14.20.3 (emphasis mine):
Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.
This means your assumption is correct.
Upvotes: 8