Core Java

Box old objects to be autoclosable

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 AutoCloser class.

We may have a legacy class (in the example this is a mocking inner class of the testing class)

1
2
3
4
5
6
7
8
9
public class NotAutoclosable {
        public NotAutoclosable() {
            opened = true;
        }
 
        public void dispose() {
            opened = false;
        }
    }

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 dispose(). (The boolean field opened is used to check later in the unit test to assert the correct functioning of the AutoCloser class.)

The use of the class looks as follows:

1
2
3
4
5
6
7
8
9
@Test
    void test() {
        final NotAutoclosable notAu;
        try (final var s = AutoCloser.useResource(new NotAutoclosable())
                .closeWith(sp -> sp.get().dispose())) {
            Assertions.assertTrue(opened);
        }
        Assertions.assertFalse(opened);
    }

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 s.

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.

The AutoCloser class is the following:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class AutoCloser<T> {
 
    private final T resource;
 
    private AutoCloser(T resource) {
        this.resource = resource;
    }
 
    public static <T> AutoCloser<T> useResource(T resource) {
        return new AutoCloser<>(resource);
    }
 
    public AutoClosableSupplier closeWith(Consumer<Supplier<T>> closer){
        return new AutoClosableSupplier(closer);
    }
 
    public class AutoClosableSupplier implements Supplier<T>, AutoCloseable {
        private final Consumer<Supplier<T>> closer;
 
        private AutoClosableSupplier(Consumer<Supplier<T>> closer) {
            this.closer = closer;
        }
 
        @Override
        public T get() {
            return resource;
        }
 
        @Override
        public void close() {
            closer.accept(this);
        }
 
    }
}

The inner 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.

Published on Java Code Geeks with permission by Peter Verhas, partner at our JCG program. See the original article here: Box old objects to be autoclosable

Opinions expressed by Java Code Geeks contributors are their own.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button