use, Closeable and Guaranteed Cleanup

use, Closeable and Guaranteed Cleanup in Kotlin: In a well-run workshop, precision tools are not simply handed out and trusted to come back.

The Analogy: The Spring-Tethered Tool Crib

In a well-run workshop, precision tools are not simply handed out and trusted to come back. Each tool at the crib window hangs on a spring tether: you draw it out to the bench, do your work, and the moment you step away from the bay the spring reels the tool straight back to the window. It does not matter whether you finished the job calmly or bolted for the exit when the fire alarm sounded -- the tether reclaims the tool either way. This is exactly what Kotlin's use function does for a resource: it hands you an open resource for the duration of a block, and guarantees the resource is closed the instant the block ends, whether that end is a normal return or a thrown exception.

When the job goes well you walk away from the bay with the finished part in hand, and the tool is already back at the window behind you. The use function mirrors this: it returns whatever value the block produced, having closed the resource first. So use is not merely a cleanup mechanism bolted on the side; it is an expression that yields the block's result while promising the close happened. The finished workpiece and the returned tool are two facts guaranteed together.

The alternative is an untethered tool that you must carry back to the window yourself on every possible way out of the bay -- including the emergency door. That is the manual try/finally: correct if you remember to put the return in the finally so it runs on every path, but easy to get wrong when there are several exits. use is the tether that makes the return automatic. When several tools are out at once, each hangs on its own tether and they reel back in reverse order of being drawn, which is precisely how nested use blocks close their resources innermost-first.

The failure that jams the whole shop is the worker who intends to return the tool "at the end of the shift" rather than letting the tether do it, then bolts during an emergency and leaves the tool lost somewhere in the bay. Now the next worker cannot draw that tool, and if enough tools go missing this way the crib runs dry. In code this is closing a resource only on the success path -- a close() written after the work but skipped when an exception fires -- so file handles, sockets, or database connections leak until the process runs out of them. There is also a subtler snag: if the tether itself catches while reeling in, that mishap must not erase the fact that your machine jammed first. Kotlin honours this by letting a body exception take precedence and recording a close failure as a suppressed exception rather than replacing the original.


Syntax or Core Structure

Any type implementing Closeable (or AutoCloseable) can be used with use, which runs a block and calls close() afterward on every path, returning the block's value.

import java.io.Closeable

class Tool(val name: String) : Closeable {
    init { println("drew " + name) }
    fun cut(): String = "cut with " + name
    override fun close() { println("returned " + name) }
}

fun main() {
    val result = Tool("saw").use { tool ->
        tool.cut()
    }
    println(result)
}

Output:

drew saw
returned saw
cut with saw

Constructing Tool("saw") prints "drew saw". The use block runs tool.cut(), which produces the string "cut with saw" but does not print it yet. As the block ends, use calls close() -- printing "returned saw" -- and only then returns the block's value to result, so "cut with saw" prints last. The order proves the point: the resource is closed before the caller ever sees the result, and the value still flows out. Whether cut had succeeded or thrown, close would have run.


Technical Depth: Guarantees, Exceptions, and Nesting

use versus manual try/finally

Both approaches guarantee cleanup, but they differ in safety and noise. The table compares them and the related types.

Aspectuse { }manual try/finally
Closes on normal exityesyes (if written)
Closes on exceptionyesyes (if in finally)
Returns block valueyesneeds a variable
Forgets a pathimpossibleeasy to miss an exit
Interface requiredCloseable/AutoCloseablenone
Suppressed close errorhandled automaticallyyou must manage it

Closeable (from java.io) and AutoCloseable both declare close(); use works with either. Prefer use over hand-written finally whenever the resource is closeable, because it cannot be routed around.

close runs even when the body throws

The whole point of use is that close happens on the exception path too, before the exception continues on to a handler.

import java.io.Closeable

class Res(val id: Int) : Closeable {
    override fun close() { println("closed " + id) }
}

fun main() {
    val msg = try {
        Res(1).use {
            println("working with " + it.id)
            throw RuntimeException("boom")
        }
    } catch (e: RuntimeException) {
        "caught: " + e.message
    }
    println(msg)
}

Output:

working with 1
closed 1
caught: boom

The block prints "working with 1" and then throws. Before that exception escapes the use, use calls close(), printing "closed 1" -- so cleanup happens even though the body failed. Only then does the exception propagate to the catch, which yields "caught: boom". The ordering shows that close ran between the throw and the handler, exactly as a finally would but without any code to remember.

Nested resources close innermost-first

When resources are nested, each use closes its own resource as its block ends, so the innermost closes first.

import java.io.Closeable

class Named(val name: String) : Closeable {
    override fun close() { println("close " + name) }
}

fun main() {
    Named("outer").use { a ->
        Named("inner").use { b ->
            println("body " + a.name + "/" + b.name)
        }
    }
}

Output:

body outer/inner
close inner
close outer

The outer resource opens, then the inner, then the innermost block runs and prints "body outer/inner". As the inner use ends it closes "inner"; then the outer use ends and closes "outer". Cleanup unwinds in the reverse of acquisition order, which matters when the inner resource depends on the outer -- you release the dependent one first.

A close failure becomes a suppressed exception

If the body throws and then close also throws, the body exception is the primary one and the close failure is attached to it as a suppressed exception, so neither is silently lost.

import java.io.Closeable

class Faulty : Closeable {
    override fun close() { throw RuntimeException("close failed") }
}

fun main() {
    val msg = try {
        Faulty().use {
            throw RuntimeException("body failed")
        }
    } catch (e: Exception) {
        val suppressed = e.suppressedExceptions.joinToString { it.message ?: "?" }
        "primary: " + e.message + " / suppressed: " + suppressed
    }
    println(msg)
}

Output:

primary: body failed / suppressed: close failed

The block throws "body failed"; while unwinding, use calls close(), which throws "close failed". Rather than let the close failure replace the original, use keeps the body exception as the primary one and records the close failure in its suppressedExceptions list. The handler reads e.message as "body failed" and finds "close failed" among the suppressed exceptions. This is the tether-snags-while-reeling case from the analogy: the secondary mishap is preserved for diagnosis but does not mask the real fault that happened first.

use balances every open with a close

A resource that tracks how many instances are open makes the guarantee visible: after a use block, the count returns to where it started.

import java.io.Closeable

var openCount = 0

class Session : Closeable {
    init { openCount += 1 }
    override fun close() { openCount -= 1 }
    fun work(): String = "did work"
}

fun main() {
    println("before: " + openCount)
    val out = Session().use { it.work() }
    println(out)
    println("after: " + openCount)
}

Output:

before: 0
did work
after: 0

Before any session exists the count is 0. Constructing Session() raises it to 1, the use block runs work() to produce "did work", and as the block ends use calls close(), dropping the count back to 0. The final line confirms the balance: every open was matched by a close. Were the close skipped -- as in a success-only manual cleanup that hit an exception -- the count would remain at 1, which is precisely the signature of a leak accumulating over many calls.


Real World Example: A Database Query Helper

A data-access helper opens a connection, runs a query, and closes the connection. The author writes it in the obvious linear order -- open, query, close -- confident that the close at the end covers cleanup.

import java.io.Closeable

class Connection(val id: Int) : Closeable {
    override fun close() { println("closed connection " + id) }
    fun query(fail: Boolean): Int {
        if (fail) throw RuntimeException("query failed")
        return 42
    }
}

fun runQuery(fail: Boolean): Int {
    val conn = Connection(1)
    println("opened connection " + conn.id)
    val result = conn.query(fail)      // if this throws, close() below is skipped
    conn.close()
    return result
}

fun main() {
    println("value = " + runQuery(false))
    val outcome = try {
        runQuery(true)
    } catch (e: RuntimeException) {
        "caught: " + e.message
    }
    println(outcome)
}

Output:

opened connection 1
closed connection 1
value = 42
opened connection 1
caught: query failed

The successful call is flawless. runQuery(false) opens connection 1, runs the query for 42, closes the connection, and returns -- the output shows "opened", "closed", then "value = 42" in order. If every query succeeded, this code would leak nothing and look perfectly correct in every review.

The failing call tells the real story through what is missing. runQuery(true) prints "opened connection 1" and then query(true) throws, so control jumps straight to the caller's catch -- and the line conn.close() is simply never reached. Notice there is no second "closed connection 1" in the output: the connection was opened and then abandoned unclosed, a leaked handle.

The genuine design flaw is placing close() only on the linear success path, exactly the untethered-tool mistake from the analogy. Every exception between opening and the manual close skips cleanup, and in a real system these leaked connections accumulate until the pool is exhausted and the application stalls -- a failure that only appears under load, long after the code looked fine in testing. The fix is to let use guarantee the close: return Connection(1).use { it.query(fail) }, which closes on the exception path as reliably as on the success path. A manual try/finally would also work, but use cannot be routed around and returns the block's value directly. The limitation worth stating plainly is that any cleanup written as a plain statement after the work is conditional on reaching that statement, and exceptions routinely ensure you do not.

Common Mistakes

  1. Closing a resource only on the success path. A close() written after the work is skipped whenever an exception fires before it, leaking the resource. Use use or put the close in a finally.
  1. Not using use for a Closeable. Hand-written cleanup can be routed around by an early return or a throw. use guarantees the close on every path and returns the block's value.
  1. Returning the resource itself from a use block. The resource is closed when the block ends, so returning it hands the caller a closed, unusable object. Return the data you extracted, not the resource.
  1. Reopening or reusing a resource after use. Once use returns, the resource is closed; any later call on it fails. Scope all work on the resource inside the block.
  1. Nesting resources in the wrong order. If an inner resource depends on an outer one, acquire the outer first so it closes last. Reversed nesting can close a dependency out from under the dependent.
  1. Swallowing the close exception and losing the real one. A failure while closing should not replace a body exception. use records it as a suppressed exception; hand-rolled cleanup must take care not to overwrite the original.
  1. Assuming a finally return is safe. Returning from a finally discards both the result and any in-flight exception, hiding cleanup and body failures alike. Never return from finally.
  1. Forgetting that GC does not close resources promptly. Relying on the garbage collector to release file handles or sockets leaves them open indefinitely. Close deterministically with use.
  1. Making a type mutable so it can be "reset" instead of closed. A resource should be opened, used, and closed; reusing one mutable instance across operations invites state leaks. Prefer a fresh resource per use.

Best Practices

  • Wrap every Closeable in use so cleanup is guaranteed on both the normal and exception paths without extra code.
  • Return extracted data from a use block, never the resource, since the resource is already closed when the block ends.
  • Acquire dependent resources inside the block of the resource they depend on, so nesting closes them innermost-first.
  • Prefer use over manual try/finally for closeables, reserving finally for cleanup of things that are not Closeable.
  • Let a body exception win over a close failure; rely on use's suppressed-exception handling rather than catching and discarding inside cleanup.
  • Implement Closeable (or AutoCloseable) on your own resource types so callers get use for free.
  • Keep the work that needs a resource entirely within its use block, avoiding any reference to the resource after it closes.
  • Close resources deterministically instead of trusting finalization or garbage collection to do it.

Practice Exercises

  1. Implement a Closeable TempFile whose close prints a message, and use it with use to confirm the close runs after the block returns its value.
  1. Reproduce the leak flaw: write a helper that closes a connection only after a query, make the query throw, and show from the output that the close is skipped. Then rewrite it with use and confirm the close now runs.
  1. Nest two use blocks over two Closeables and confirm from the printed order that the inner resource closes before the outer.
  1. Write a use block whose body throws, catch the exception outside, and confirm from the output that close ran before the catch handled it.