WW.
WW.

Reputation: 24291

try-with-resources: Does Java make any guarantees about the order of calls to .close()?

When using a try-with-resources in Java 7, are there any guarantees about the order in which .close() is called?

Here's some sample code from Oracle showing this feature:

try (
  java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
  java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {

  // Enumerate each entry

  for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {

    // Get the entry name and write it to the output file

    String newLine = System.getProperty("line.separator");
    String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
    writer.write(zipEntryName, 0, zipEntryName.length());
  }

Both zf.close() and writer.close() will be called. Is the order guaranteed?

Upvotes: 2

Views: 256

Answers (1)

Thilo
Thilo

Reputation: 262534

It is in the opposite order of declaration, closing from the inside to the outside.

Upvotes: 4

Related Questions