javahttpclientapache-httpclient-4.xsingle-threaded

How can I reuse same HttpClient Connection in my Single threaded Java Client Application?


I am working on one Single threaded java client . It is making One HttpClient connection to hit some API's. I want to use same connection object to hit another set of API's after sometime. It is running on single JVM and JVM is running throught the process . Is there anything that Apache provides that I can use to keep that connection object a live and use to hit another set of API's from it. JVM is running throught the process but once I create a connection object and come second time to hit another API's it make a new object. I want to use the existing object that I have created earlier.

I am using the below method to make the HttpClient Connection.

public static CloseableHttpClient getConnection() {
        BasicHttpClientConnectionManager conMgr = new BasicHttpClientConnectionManager();
        HttpClientBuilder clientBuilder = HttpClientBuilder.create().disableAutomaticRetries().useSystemProperties()
                .disableCookieManagement().disableRedirectHandling().setConnectionManager(conMgr);
        return clientBuilder.build();
    }

If you know anyway that I can use to reuse this connection object rather than creating new second time .Please Update.


Solution

  • Well in its simplest terms, you could create it in a static public context:

    public class MainApplication{
    
        private static BasicHttpClientConnectionManager conMgr = new BasicHttpClientConnectionManager();
        public static CloseableHttpClient closeableHttpClient =  HttpClientBuilder.create().disableAutomaticRetries().useSystemProperties()
                .disableCookieManagement().disableRedirectHandling().setConnectionManager(conMgr).build();
    
    
        public void noneStaticMethodUsingHttpClient() throws IOException {
                closeableHttpClient.close();
        }
    
    }
    

    Then it is shared across your application, and will only be initialized on your application startup.

    However, I am not a fan of public static, therefore I will also recommend you look at the Singleton pattern which you can use to wrap your static initialization.

    https://refactoring.guru/design-patterns/singleton