Course contentsShow
← Java
Lesson 836 of 2,87020. Try-With-Resources and Resource ManagementFree lesson

Closing Order of Resources

Resources close in reverse order: last declared closes first, ensuring proper cleanup dependencies.

What You'll Learn

You'll learn the precise order in which Java closes resources in a try-with-resources statement and why this order matters for proper cleanup.

The Closing Order Rule

When you declare multiple resources in a try-with-resources statement, Java closes them in reverse order of their declaration. This means the last resource declared closes first, and the first resource declared closes last.

Think of it like stacking plates: you declare resources from bottom to top, and Java cleans them up from top to bottom.

Why Reverse Order Matters

This reverse order isn't arbitrary—it handles cleanup dependencies correctly. Often, later resources depend on earlier ones. For example, if you open a file connection first and then wrap it in a buffered reader, the buffered reader must close before the underlying file connection. The reverse-order closing ensures this happens automatically.

try (FileInputStream fis = new FileInputStream("data.txt");
     BufferedInputStream bis = new BufferedInputStream(fis)) {
    
    // Use the resources
    int data = bis.read();
}
// Closing happens here automatically:
// 1. bis.close() is called FIRST
// 2. fis.close() is called SECOND

In this example, bis depends on fis. If fis closed first, bis would fail during its cleanup. Java's reverse-order closing prevents this problem.

The Analogy

Imagine building with building blocks: you place the foundation first, then add layers on top. When dismantling, you remove the top layers first, then finally the foundation. You can't remove the foundation while upper layers still depend on it.

Key Takeaway: In try-with-resources, resources close in reverse declaration order (last declared closes first), ensuring dependent resources clean up safely before the resources they depend on.