How does Java decide when to reclaim an object, and what does that mean for resources you must release explicitly?
Java decides when to reclaim an object by looking at whether anything can still reach it. When nothing points at an object any more, the runtime may throw it away and reuse the memory. There is no moment that you control and no call that you make.
And what does that mean for the resources you must release? It means you cannot rely on the runtime to do it for you. A file handle, a socket or a database connection has to be released by you, at a moment that you choose, because the runtime knows nothing about them.
public class Main {
public static void main(String[] args) {
try (Connection c = new Connection("orders-db")) {
c.execute("select 1");
}
// The connection is closed here, even if the body threw.
System.out.println("done");
}
}
And the construct to use is the try-with-resources, which is the block in the middle. You put the resource in the parentheses after the word try, and Java closes it when the block ends, whether it ended normally or because something was thrown.
public class Connection implements AutoCloseable {
private final String name;
public Connection(String name) {
this.name = name;
}
public void execute(String sql) {
System.out.println("running " + sql + " on " + name);
}
@Override
public void close() {
System.out.println("closing " + name);
}
}
And there are three reasons why the try-with-resources is the right way to do it.
the reason what it means
---------------------------- ----------------------------------------
it always closes the close happens even when the body
throws
it closes in the right order the resources close in the reverse
order that you opened them
the code is short there is no finally block and no
nested try
And there is one detail worth knowing about. The resource has to implement the interface AutoCloseable, and then the compiler writes the closing code for you and it handles the exceptions properly. If you write the closing by hand in a finally block then you have to handle the case where the close itself throws, and people get that wrong all the time.
So the rule to remember is this. The runtime frees the memory and nothing else, so you release the resources yourself with try-with-resources.
The last question in this topic is about finalizers.