Skip to content

Commit 1fd3869

Browse files
committed
Make sure that httpClient frees resources when Send Grid Client goes out of scope
1 parent cbeae1a commit 1fd3869

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

src/main/java/com/sendgrid/Client.java

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -278,18 +278,20 @@ public Response delete(Request request) throws URISyntaxException, IOException {
278278
}
279279

280280
private Response executeApiCall(HttpRequestBase httpPost) throws IOException {
281-
CloseableHttpResponse serverResponse = httpClient.execute(httpPost);
282281
try {
283-
Response response = getResponse(serverResponse);
284-
if(response.getStatusCode() >= 300) {
285-
//throwing IOException here to not break API behavior.
286-
throw new IOException("Request returned status Code "+response.getStatusCode()+"Body:"+response.getBody());
282+
CloseableHttpResponse serverResponse = httpClient.execute(httpPost);
283+
try {
284+
Response response = getResponse(serverResponse);
285+
if(response.getStatusCode() >= 300) {
286+
//throwing IOException here to not break API behavior.
287+
throw new IOException("Request returned status Code "+response.getStatusCode()+"Body:"+response.getBody());
288+
}
289+
return response;
290+
} finally {
291+
serverResponse.close();
287292
}
288-
return response;
289293
} catch(ClientProtocolException e) {
290294
throw new IOException(e.getMessage());
291-
} finally {
292-
serverResponse.close();
293295
}
294296
}
295297

@@ -323,4 +325,15 @@ public Response api(Request request) throws IOException {
323325
throw new IOException(errors.toString());
324326
}
325327
}
328+
329+
@Override
330+
public void finalize() throws Throwable {
331+
try {
332+
this.httpClient.close();
333+
} catch(IOException e) {
334+
throw new Throwable(e.getMessage());
335+
} finally {
336+
super.finalize();
337+
}
338+
}
326339
}

0 commit comments

Comments
 (0)