Closing long-lived resources in Kotlin – Glade Diviney – Medium
source link: https://medium.com/@gladed/closing-long-lived-resources-in-kotlin-4e0b8e6ffbb7
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Closing long-lived resources in Kotlin
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()
orstop()
twice? - What happens if
close()
throws? - Can
resource
be garbage collected afterMyClass
is stopped? - Is
MyClass
thread-safe with respect toresource
?
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.
AutoCloser
is also included for wrapping AutoCloseable
types.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK