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 ...
Get Programming Groovy 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.