Jiri Kremser
Jiri Kremser

Reputation: 12837

try-with-resource vs finally precedence

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:

  1. closing the SequenceWriter
  2. closing the PipedOutputStream
  3. closing the Page
  4. running the callback

Am I wrong here?

Upvotes: 5

Views: 1569

Answers (1)

Tunaki
Tunaki

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

Related Questions