Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to close async resteasy client call

I have the following code:

var threadsWaiter = new CountDownLatch(customers.size());
for(var c: List<Customer> customers) {
   sendSms(c.phoneNr, threadsWaiter)
}
threadsWaiter.await();

public void sendSms(String phoneNr, CountDownLatch threadsWaiter) {
  ResteasyClientBuilder.newClient()
            .target(smsUrl)                
            .queryParam("to", phoneNr)
            .queryParam("message", message)
            .request()
            .async()
            .get(new InvocationCallback<String>() {
                @Override
                public void completed(String res) {
                    threadsWaiter.countDown();
                    if (res != null && !res.contains("code=ok") {
                        logger.error("Received sms response for '{}'\n{}", phoneNr, res);
                    } else {                            
                        logger.debug("Sms sent to '{}'", phoneNr);
                    }
                }

                @Override
                public void failed(Throwable throwable) {
                    threadsWaiter.countDown();
                    logger.error("Error sending sms for {}: \n{}", phoneNr, throwable.getMessage());
                }
            });
}

And I get the following warning from the console:

RESTEASY004687: Closing a class org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine instance for you. Please close clients yourself.

What is the proper way to close this client call? Because this might be a source for a potential memory leak in the application. And even I get this warning from RestEasy that it closes the client automatically for me, but I've a strong feeling that it doesn't close all the clients since I see a huge memory increase in the metrics and this doesn't "go down" after a while.

I've placed the rest client call between try-finally, but the problem with this is that you can close the client before the call is finished. Is it ok to close the client in the completed(..) and the failed(..) methods in the InvocationCallback or is there a better way?

like image 736
Serkan Avatar asked Jan 28 '20 21:01

Serkan


1 Answers

If the client definition via JaxRS interface is ok for you, then the answer from rowing-goul above is the way to go. Injected clients are automatically closed by Quarkus Arc during bean destroyer process. If you create clients manually, then you must close them explicitly - best way is try - finally

like image 188
yntelectual Avatar answered Sep 18 '22 14:09

yntelectual