Resources and why they must be closed
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A resource is something your program borrows from the operating system and must give back: an open file, a network connection, a database connection, a lock. Java's garbage collector frees memory for you, but it does not give these back on time, so you close them yourself.
What a resource is: file handles, connections, locks
A resource is an object that holds something outside the JVM, such as an open file or network connection, and must be closed when you are done with it.
A resource is anything outside plain Java memory that your program holds open and must release when done. The operating system (OS) is the main program of the computer, such as Windows, macOS or Linux.
Example 1 · Open, use and close a real file
import java.io.BufferedReader;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class FirstResourceDemo { public static void main(String[] args) throws IOException { Path folder = Files.createTempDirectory("marks"); Path file = folder.resolve("marks.txt"); Files.writeString(file, "Asha,87\nRavi,72\n");
BufferedReader reader = Files.newBufferedReader(file); // the OS opens the file System.out.println("Opened " + file.getFileName()); System.out.println("First line: " + reader.readLine()); reader.close(); // the OS gets it back System.out.println("Closed " + file.getFileName());
Files.delete(file); Files.delete(folder); System.out.println("Cleaned up"); }}Opened marks.txt First line: Asha,87 Closed marks.txt Cleaned up
What this code does
Files.newBufferedReader(file)asks the OS to open the file and gives back a reader that holds the handle. The Paths and Files module coversFilesin detail.reader.close()hands the file back. IfreadLine()threw an exception, theclose()line would be skipped: the next lesson fixes exactly that.
Example 2 · Which objects are resources?
import java.io.BufferedReader;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Scanner;import java.util.concurrent.locks.ReentrantLock;
public class FindResourcesDemo { static void check(String name, Object obj) { String verdict = (obj instanceof AutoCloseable) ? "resource: close it" : "plain object"; System.out.printf("%-15s %s%n", name, verdict); }
public static void main(String[] args) throws Exception { Path temp = Files.createTempFile("fees", ".txt"); BufferedReader reader = Files.newBufferedReader(temp); Scanner scanner = new Scanner("1200 3500");
check("String", "UPI-4521"); check("ArrayList", new ArrayList<String>()); check("BufferedReader", reader); check("Scanner", scanner); check("ReentrantLock", new ReentrantLock());
reader.close(); scanner.close(); Files.delete(temp); }}String plain object ArrayList plain object BufferedReader resource: close it Scanner resource: close it ReentrantLock plain object
What this code does
obj instanceof AutoCloseableis a quick test: a class that implementsAutoCloseablesays "callclose()on me when you are done".- A
ReentrantLockis a resource too, but it is notAutoCloseable: you release it withunlock(). The last lessons of this module show how to handle it.
When Java opens a file, the OS gives it a file handle: a small ticket that says "this program has this file open". Calling close() returns the ticket. Until then the OS keeps the file open for your program, even if your code never touches it again.
- Files:
BufferedReader,FileInputStream,Scanneron a file. - Connections: a network socket, a database connection, an HTTP connection.
- Locks: a
ReentrantLockthat other threads wait for until you callunlock(). - Most resource classes implement the interface
AutoCloseable, which has one method:close().
The operating system's limit on open files
The OS lets each program hold only a limited number of open handles at once. On Linux the default is often 1024 per process; macOS uses a similar soft limit.
Example 3 · A simplified model of the open-file limit
import java.io.IOException;
class PretendOs { static final int LIMIT = 3; // real limits are much bigger, often 1024 or more static int open = 0;
static void openFile(String name) throws IOException { if (open == LIMIT) { throw new IOException(name + ": Too many open files"); } open++; System.out.println(" open " + name + " (open now: " + open + ")"); }
static void closeFile(String name) { open--; System.out.println(" close " + name + " (open now: " + open + ")"); }}
public class OpenLimitDemo { public static void main(String[] args) { String[] files = {"cse.txt", "ece.txt", "mech.txt", "civil.txt"};
System.out.println("Run 1: close each file after use"); try { for (String f : files) { PretendOs.openFile(f); PretendOs.closeFile(f); } } catch (IOException e) { System.out.println(" Failed: " + e.getMessage()); }
System.out.println("Run 2: forget to close"); try { for (String f : files) { PretendOs.openFile(f); } } catch (IOException e) { System.out.println(" Failed: " + e.getMessage()); } }}Run 1: close each file after use open cse.txt (open now: 1) close cse.txt (open now: 0) open ece.txt (open now: 1) close ece.txt (open now: 0) open mech.txt (open now: 1) close mech.txt (open now: 0) open civil.txt (open now: 1) close civil.txt (open now: 0) Run 2: forget to close open cse.txt (open now: 1) open ece.txt (open now: 2) open mech.txt (open now: 3) Failed: civil.txt: Too many open files
What this code does
- In run 1 each file is closed before the next one opens, so the count never goes above 1 and all four files work.
- In run 2 nothing is closed. The fourth open fails with the same message a real OS gives, even though the program is only reading one file at a time.
Windows allows far more, but the limit still exists, and memory runs out long before it.
A program that closes each file after use can open millions of files in its lifetime, one after another. A program that forgets to close stays under the limit only until it has opened enough files. Example 3 is a simplified model with a limit of 3, so the effect is easy to see.
Leaks and the "too many open files" error
A resource leak is a resource that was opened and never closed. The program still works, so the leak hides.
Example 4 · A leak hidden behind an early return
class PretendFile { static int stillOpen = 0; private final String name;
PretendFile(String name) { this.name = name; stillOpen++; }
String firstLine() { return name.startsWith("empty") ? "" : "header of " + name; }
void close() { stillOpen--; }}
public class LeakDemo { static String readHeader(String name) { PretendFile f = new PretendFile(name); String line = f.firstLine(); if (line.isEmpty()) { return "(no header)"; // leak: we return before close() } f.close(); return line; }
public static void main(String[] args) { String[] names = {"day1.csv", "empty-day2.csv", "day3.csv", "empty-day4.csv"}; for (String n : names) { System.out.println(n + " -> " + readHeader(n)); } System.out.println("Files still open: " + PretendFile.stillOpen); }}day1.csv -> header of day1.csv empty-day2.csv -> (no header) day3.csv -> header of day3.csv empty-day4.csv -> (no header) Files still open: 2
What this code does
- Every call returns the right text, so the program looks correct. But for the two empty files
returnruns beforef.close(). Files still open: 2is the leak. In a server that reads such files all day, this number only grows.
It shows up hours later, when the limit is reached and every new open fails with an error such as java.nio.file.FileSystemException: marks.txt: Too many open files on Linux or macOS.
Leaks rarely come from forgetting close() completely. They come from paths that skip it: an early return, a break out of a loop, or an exception thrown between open and close. The garbage collector may clean up some handles one day, but you cannot know when, so never rely on it.
A locked file on Windows that cannot be deleted
Windows adds a second problem. While a program holds a file open with the older classes such as FileInputStream or FileReader, Windows locks the file: no program, not even yours, can delete or rename it.
Example 5 · Windows refuses to delete an open file
import java.io.FileInputStream;import java.io.IOException;import java.nio.file.FileSystemException;import java.nio.file.Files;import java.nio.file.Path;
public class WindowsLockDemo { public static void main(String[] args) throws IOException { Path file = Files.createTempFile("hall-ticket", ".txt"); Files.writeString(file, "Roll 21, Hall B");
FileInputStream in = new FileInputStream(file.toFile()); System.out.println("Read " + in.readAllBytes().length + " bytes");
try { Files.delete(file); // the stream is still open System.out.println("Deleted while still open"); } catch (FileSystemException e) { System.out.println("Delete failed: " + e.getReason()); }
in.close(); System.out.println("After close, deleted: " + Files.deleteIfExists(file)); }}Read 15 bytes Delete failed: The process cannot access the file because it is being used by another process After close, deleted: true
What this code does
- On Windows,
Files.deletefails while theFileInputStreamis open. Afterin.close()the same file deletes at once. - On Linux or macOS the first delete works and the program prints
Deleted while still openandAfter close, deleted: false.
The delete fails with FileSystemException and the reason "The process cannot access the file because it is being used by another process". Linux and macOS allow the delete, so code that leaks can pass every test on a Linux laptop and fail on a Windows lab computer. Closing first fixes both.
Next step
Check your understanding
12 quick questions