diff --git a/examples/src/main/java/io/kubernetes/client/examples/WatchExample.java b/examples/src/main/java/io/kubernetes/client/examples/WatchExample.java index 4b5afab4d0..907cba1ea0 100644 --- a/examples/src/main/java/io/kubernetes/client/examples/WatchExample.java +++ b/examples/src/main/java/io/kubernetes/client/examples/WatchExample.java @@ -39,8 +39,12 @@ public static void main(String[] args) throws IOException, ApiException { null, null, null, null, null, 5, null, null, Boolean.TRUE, null, null), new TypeToken>() {}.getType()); - for (Watch.Response item : watch) { - System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName()); + try { + for (Watch.Response item : watch) { + System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName()); + } + } finally { + watch.close(); } } } diff --git a/util/src/main/java/io/kubernetes/client/util/Watch.java b/util/src/main/java/io/kubernetes/client/util/Watch.java index 7d049a3de6..99b651bc20 100644 --- a/util/src/main/java/io/kubernetes/client/util/Watch.java +++ b/util/src/main/java/io/kubernetes/client/util/Watch.java @@ -32,7 +32,10 @@ * CoreV1Api.listNamespaceCall and set watch to True and watch the changes to namespaces. */ public class Watch - implements Iterable>, Iterator>, java.io.Closeable { + implements Iterable>, + Iterator>, + java.io.Closeable, + AutoCloseable { /** * Response class holds a watch response that has a `type` that can be ADDED, MODIFIED, DELETED @@ -82,13 +85,13 @@ public static Watch createWatch(ApiClient client, Call call, Type watchTy com.squareup.okhttp.Response response = call.execute(); if (!response.isSuccessful()) { String respBody = null; - if (response.body() != null) { - try { + try (ResponseBody body = response.body()) { + if (body != null) { respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException( - response.message(), e, response.code(), response.headers().toMultimap()); } + } catch (IOException e) { + throw new ApiException( + response.message(), e, response.code(), response.headers().toMultimap()); } throw new ApiException( response.message(), response.code(), response.headers().toMultimap(), respBody);