4.5 Using Closures for Resource Cleanup
Java’s automatic garbage collection is a mixed blessing. We don’t have to worry about resource deallocation, provided we release references.
But there’s no guarantee of when the resource will actually be cleaned up, because it’s at the
discretion of the garbage collector. In certain situations, we might want the cleanup
to happen straightaway. This is the reason we see methods such as
close
and
destroy
on resource-intensive
classes.
One problem, though, is that the users of our class may forget to call these methods.
Closures can help ensure that the methods get called.
In the following code we create a FileWriter and write some data, but ignore the call to
close on it. If we run this code, the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access