In this post I’ll show some of the problems with managing long-lived resources, and propose a simple utility class to help you solve them.

Quick, how many bugs can you spot in the following code:

What happens if someone calls start() or stop() twice?

or twice? What happens if close() throws?

throws? Can resource be garbage collected after MyClass is stopped?

be garbage collected after is stopped? Is MyClass thread-safe with respect to resource ?

Some things are just hard to close safely.

Let’s address these issues:

Yuck. This works, but it’s a lot of boilerplate, exception-catching noise, a dangerous-looking var , potential synchronization issues, and ugly null objects.

We can do better with a utility class I call Closer (defined below). But first, let’s see it in action in a real-world(-ish) Android use case. Here, we create and initialize a MulticastLock , but only if it doesn’t already exist. And later we call its release() method, but only if it’s still hanging around:

Closer.kt

Here’s an implementation of Closer for use in your own projects.