Since Java 7 we can use try-with-resources and have any object automatically closed that implements the
Autocloseable interface. If the resource is
Autocloseable. Some of the classes need some wrap-up but are not
Autocloseable. These are mainly old classes in some legacy framework that still get in our way to make us trip up. Nobody is using Struts any more, but still, there are enough old frameworks that are there lurking in the dark and with which we have to live. I recently had that experience and I was so motivated that I created a simple
We may have a legacy class (in the example this is a mocking inner class of the testing class)
which is not auto-closeable as the name also implies. It does not implement the
Autocloseable interface and it does not have a
close() method. It has to be disposed calling the aptly named method
opened is used to check later in the unit test to assert the correct functioning of the
The use of the class looks as follows:
We create the resource using the constructor of the inner class and we also define a
Consumer that will “close” the resource. This consumer will get the same
Supplier that is stored in the variable
Side note: this functional argument has to be a consumer and cannot be a
Runnable using the variable
s because that variable is not initialized when the lambda expression is evaluated as a lambda expression. When it is going to be used it will already be defined but that is too late for the Java compiler, it does not trust the programmer that much and usually, it does it with good reason.
AutoCloser class is the following:
AutoClosableSupplier class is used because we do not want the programmer accidentally forget to specify the lambda that will finally close the resource.
This is nothing really serious. It is just a programming style that moves the closing of the resource close to the opening of the resource a bit like the
deferred statement in the Go language.
Opinions expressed by Java Code Geeks contributors are their own.