# How to properly close a connection in a Java API Client?

**URL:** https://discuss.elastic.co/t/how-to-properly-close-a-connection-in-a-java-api-client/314995
**Category:** Elasticsearch
**Tags:** language-clients
**Created:** [September 23, 2022, 6:54am UTC](https://discuss.elastic.co/t/how-to-properly-close-a-connection-in-a-java-api-client/314995 "2022-09-23T06:54:49Z")
**Posts on this page:** 7
**Page:** 1

<div class="post-metadata">

### Author: ![jacksparrow414](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jacksparrow414/32/111161_2.png) [@jacksparrow414](https://discuss.elastic.co/u/jacksparrow414)
#### Post date: [September 23, 2022, 6:54am UTC](https://discuss.elastic.co/t/how-to-properly-close-a-connection-in-a-java-api-client/314995/1 "2022-09-23T06:54:49Z")

</div>

Configuration Sample Code

```auto
@ApplicationScoped
public class ElasticSearchConfiguration {

    private static ElasticsearchClient client;

    private static synchronized void connectElasticSearchCluster() {
        if (Objects.nonNull(client)) {
            return;
        }
        final CredentialsProvider credentialsProvider =
                new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(ELASTIC_USER, ELASTIC_PASSWORD));
        RestClientBuilder builder = RestClient.builder(initializeHttpHost())
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                        .setDefaultCredentialsProvider(credentialsProvider));

        // init RestClient only once
        RestClient restClient = builder.build();
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        client = new ElasticsearchClient(transport);
    }

    private static HttpHost[] initializeHttpHost() {
        List<String> hosts = Splitter.on(",").splitToList(ELASTIC_CLUSTER_HOST);
        List<HttpHost> result = Lists.newArrayList();
        hosts.forEach(item -> {
            HttpHost httpHost = HttpHost.create(item);
            result.add(httpHost);
        });
        return result.toArray(new HttpHost[hosts.size()]);
    }

    public ElasticsearchClient openConnection() {
        if (Objects.isNull(client) && ENABLE_ELASTIC) {
            connectElasticSearchCluster();
        }
        return client;
    }
}

```

Usage Sample Code

```auto
@ApplicationScoped
public class SearchService {

    @Inject
    private ElasticSearchConfiguration elasticSearchConfiguration;

    private List<Long> paginationQuery(List<String> queryIndexNames, Query query) {

	    ElasticsearchClient elasticsearchClient = elasticSearchConfiguration.openConnection();

		SearchResponse<TestDocument> searchResponse = elasticsearchClient.search(builder.build(), TestDocument.class);
		...
        return new ArrayList<>();
    }
}

```

According to the [official documentation](https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/java-rest-low-usage-initialization.html)

> The RestClient class is thread-safe and ideally has the same lifecycle as the application that uses it

So I think RestClient should be singleton.for the same reason, I think Java API clients, such as ElasticsearchClient, should also be singleton.

When the application shut down, I want to close the ElasticsearchClient, I found that there is no close method, only the client.\_transport().close() method; should I use this method? Or should I make RestClient also a static property and use RestClient.close() method, if so, doesn't ElasticsearchClient need to be closed?

---

<div class="post-metadata">

### Author: ![jacksparrow414](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jacksparrow414/32/111161_2.png) [@jacksparrow414](https://discuss.elastic.co/u/jacksparrow414)
#### Post date: [October 11, 2022, 12:08am UTC](https://discuss.elastic.co/t/how-to-properly-close-a-connection-in-a-java-api-client/314995/2 "2022-10-11T00:08:34Z")

</div>

Can someone answer this question?

---

<div class="post-metadata">

### Author: ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)
#### Post date: [October 11, 2022, 4:02am UTC](https://discuss.elastic.co/t/how-to-properly-close-a-connection-in-a-java-api-client/314995/3 "2022-10-11T04:02:49Z")

</div>

Welcome!

You only need to close the ElasticsearchTransport object.

---

<div class="post-metadata">

### Author: ![jacksparrow414](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jacksparrow414/32/111161_2.png) [@jacksparrow414](https://discuss.elastic.co/u/jacksparrow414)
#### Post date: [October 12, 2022, 9:08am UTC](https://discuss.elastic.co/t/how-to-properly-close-a-connection-in-a-java-api-client/314995/4 "2022-10-12T09:08:39Z")

</div>

invoke client.\_transport().close() method,right?

---

<div class="post-metadata">

### Author: ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)
#### Post date: [October 12, 2022, 10:17am UTC](https://discuss.elastic.co/t/how-to-properly-close-a-connection-in-a-java-api-client/314995/5 "2022-10-12T10:17:58Z")

</div>

I'd make `transport` a private static field of the class and call `transport.close()`.

---

<div class="post-metadata">

### Author: ![jacksparrow414](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jacksparrow414/32/111161_2.png) [@jacksparrow414](https://discuss.elastic.co/u/jacksparrow414)
#### Post date: [October 12, 2022, 11:58am UTC](https://discuss.elastic.co/t/how-to-properly-close-a-connection-in-a-java-api-client/314995/6 "2022-10-12T11:58:10Z")

</div>

Thank you very much for your answer 👍 :+1

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [November 9, 2022, 11:58am UTC](https://discuss.elastic.co/t/how-to-properly-close-a-connection-in-a-java-api-client/314995/7 "2022-11-09T11:58:37Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
