DeferHandle
DeferHandle is a handle returned by Scope.defer that allows cancelling a registered finalizer before the scope closes:
abstract class DeferHandle {
def cancel(): Unit
}
When Scope#defer(cleanup) is called, the cleanup action is registered and a DeferHandle is returned. This handle can be used to remove that finalizer early, preventing it from running when the scope closes. This is useful when a resource is explicitly released before the scope ends, and running the finalizer again would be unnecessary or harmful.
Construction
DeferHandle is not instantiated directly. Instead, it is created by calling Scope#defer with a cleanup action:
import zio.blocks.scope.{Scope, DeferHandle}
trait Scope {
def defer(cleanup: => Unit): DeferHandle
}
The following example demonstrates creating a DeferHandle:
import zio.blocks.scope.Scope
Scope.global.scoped { scope =>
import scope._
val handle = defer {
println("This cleanup will run when scope closes, unless cancelled")
}
// The handle can now be used to cancel the cleanup
handle.cancel()
}
Core Operations
The DeferHandle#cancel method removes the registered finalizer so it will not run when the scope closes:
trait DeferHandle {
def cancel(): Unit
}
This method is:
- Thread-safe: Can be called from any thread without synchronization
- Idempotent: Calling it multiple times has the same effect as calling once
If the scope has already closed (and the finalizer has already run or been discarded), calling DeferHandle#cancel is a no-op. In the following example, we register a cleanup action, then cancel it before the scope closes:
import zio.blocks.scope.Scope
import java.io.ByteArrayOutputStream
Scope.global.scoped { scope =>
import scope._
val buffer = allocate(ByteArrayOutputStream())
val closeHandle = defer {
println("Auto-closing buffer")
$(buffer)(_.close())
}
// Manually close the buffer
$(buffer)(_.close())
// Cancel the automatic finalizer since we already closed it
closeHandle.cancel()
}
Use Cases
DeferHandle is useful in several common scenarios: