Groovy withCloseable
withCloseable passes an AutoCloseable resource to a closure, returns the closure's result, and closes the resource when processing finishes.
A simple example
withCloseable
- Start with A reader containing A
- Do this Read inside a managed block
- Result A, then reader closed
Syntax
reader.withCloseable { stream -> stream.readLine() }
Run this example in Groovy
Save the program as Lesson.groovy. Use Groovy 4 on the JVM.
groovy Lesson.groovy
Close a reader after processing its first record
A program opens a reader to process records and can finish before reaching the last one. Keep operations inside the reader's lifetime and release the open resource when the work completes.
def reader = new BufferedReader(new StringReader("first\nsecond"))
def first = reader.withCloseable { stream -> stream.readLine() }
println first
try {
reader.readLine()
} catch (IOException ex) {
println 'closed'
}
first closed
Return a value obtained inside the closure. Reading from the same reader afterward fails because the underlying resource has already been closed.
Groovy documentation for withCloseable
Finish a rehearsal import
A music teacher reads an attendance note using a scoped reader. The operator finishes reading inside a managed resource scope. What is the reader’s state after leaving the scope?
Complete a shift handover
A supervisor reads a handover note to the end inside a cleanup block. The operator finishes reading inside a managed resource scope. What is the reader’s state after leaving the scope?