Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Making Sure Closeable Objects Are Closed [Snippet]

DZone's Guide to

Groovy Goodness: Making Sure Closeable Objects Are Closed [Snippet]

See how Groovy handles classes and objects that implement the Closeable interface and how you can ensure your closed methods are invoked.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

If a class implements the Closeable interface, Groovy adds the withCloseable method to the class. The withCloseable method has a closure as an argument. The code in the closure is executed and then the implementation of the close method of the Closeable interface is invoked. The Closeable object is passed as an argument to the closure so we can refer to it inside the closure.

In the following example, we have two objects that implement the Closeable interface. By using withCloseable, we know for sure the close method is invoked after all the code in the closure is executed:

@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.5.3')
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.client.methods.HttpGet

// HttpClientBuilder.create().build() returns a CloseableHttpClient
// that implements the Closeable interface. Therefore we can use
// the withCloseable method to make sure the client is closed
// after the closure code is executed. 
HttpClientBuilder.create().build().withCloseable { client ->
    final request = new HttpGet('http://www.mrhaki.com')

    // The execute method returns a CloseableHttpResponse object
    // that implements the Closeable interface. We can use
    // withCloseable method to make sure the response is closed
    // after the closure code is executed.
    client.execute(request).withCloseable { response ->
        assert response.statusLine.statusCode == 200
    }
}


Written with Groovy 2.4.12.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,groovy ,closeable

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}