Closing JAX-RS Response with try-with-resources

A JAX-RS Response implements AutoCloseable. It can either be closed explicitly, or via try-with-resources:


import static org.junit.jupiter.api.Assertions.assertNotNull;
import javax.inject.Inject;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class AutocloseableResponseIT {

    @Inject
    @RestClient
    WebsiteClient client;

    @Test
    void closeExplicitly(){
        var response = this.client.getContent();
        var content = response.readEntity(String.class);
        response.close();
        assertNotNull(content);
    }

    @Test
    void autoClose(){
        try(var response = this.client.getContent()){
            var content = response.readEntity(String.class);
            assertNotNull(content);
        }
    }
}

The corresponding client (Rest Client for MicroProfile) used in this example is:


import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;

@RegisterRestClient(baseUri = "http://localhost:8080")
public interface WebsiteClient {
    
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    Response getContent();
}

Too many "open" Responses may lead to blocking behavior.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License