Library contents

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

  1. Start with A reader containing A
  2. Do this Read inside a managed block
  3. Result A, then reader closed
The resource manager closes the reader when the block ends.

Syntax

Groovy 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.

First output linefirst
Lesson.groovy
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'
}
Output
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

Advertisements

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?

GivenRead “Attendance” → leave scope
Worked resultClosed

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?

GivenRead “Counted” → leave scope
Worked resultClosed