On doing a code analysis of the below code in SonarQube, I found that i suggests to close the HttpClient.
import org.apache.http.impl.client.CloseableHttpClient;
public void request() {
CloseableHttpClient httpclient = null;
try {
httpclient = HttpClients.createDefault();
/**
* Rest of the code
*/
} catch(IOException e) {
LOGGER.error("Error in processing : {}", e.getMessage(), e);
} finally {
try {
if(httpclient != null) {
httpclient.close();
}
} catch(IOException e) {
LOGGER.error("Error in closing client : {}", e.getMessage(), e);
}
}
}
SonarQube still complains that httpclient
should be closed, even though I am closing it in the finally
block.
The error given by SonarQube:
Close this "CloseableHttpClient".
Java - 1.8 SonarQube - 5.6
Any ideas what I might be doing wrong. Thanks
Use a try with resources