1

Does the termination of a program effectively clean up resources or it is still needed to be done explicitly? I would get rid of the boilerplate if it has no benefit.

I understand the need in case of long-lived program where the resource usage is shorter than the lifecycle of the program. But what is the case when the resource (like a singleton HTTP client) is used until the end?

1. No explicit cleanup

Does this version clean things up when the program exits?

public static void main(String[] args) {
    CloseableHttpClient client = HttpClients.createDefault();

    // execute requests
}

2. Cleanup using try with resources

This version obviously does clean up but requires additional code.

public static void main(String[] args) {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        // execute requests
    } catch (IOException e) {
        // exception handling
    }
}
Martin Tarjányi
  • 8,863
  • 2
  • 31
  • 49

1 Answers1

0

Latest update on apachec doc is to create inside try:

try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

A more full answer explains in more details

The answer is that the close method is used to close internal state. Some of the implementations of HTTPClient(in the httpclient lib) can be configured to use persistent resources such as PooledHttpClientConnectionManager for pooled connections and without such a method you could not clean up these resources if needed

Ori Marko
  • 56,308
  • 23
  • 131
  • 233