{"id":714,"date":"2022-02-08T09:29:09","date_gmt":"2022-02-08T09:29:09","guid":{"rendered":"https:\/\/vukieuanh.com\/?p=714"},"modified":"2022-02-11T04:02:39","modified_gmt":"2022-02-11T04:02:39","slug":"using-try-with-resources","status":"publish","type":"post","link":"https:\/\/vukieuanh.net\/index.php\/2022\/02\/08\/using-try-with-resources\/","title":{"rendered":"Using Try-With-Resources"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/vukieuanh.com\/wp-content\/uploads\/2022\/02\/Screen-Shot-2022-02-09-at-11.37.09-1024x679.png\" alt=\"\" class=\"wp-image-720\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Gi\u1edbi thi\u1ec7u<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">T\u1eeb phi\u00ean b\u1ea3n Java 7, ch\u00fang ta c\u00f3 th\u1ec3 s\u1eed d\u1ee5ng t\u00ednh n\u0103ng try-with-resource v\u1edbi nh\u1eefng class c\u00f3 s\u1eb5n c\u1ee7a Java. <strong>Resource<\/strong>&nbsp;l\u00e0 m\u1ed9t \u0111\u1ed1i t\u01b0\u1ee3ng \u0111\u1ea1i di\u1ec7n cho t\u00e0i nguy\u00ean c\u1ea7n ph\u1ea3i \u0111\u01b0\u1ee3c \u0111\u00f3ng l\u1ea1i m\u1ed7i khi s\u1eed d\u1ee5ng n\u00f3. V\u00ed d\u1ee5 file, k\u1ebft n\u1ed1i CSDL. Trong JDBC, ta hay th\u1ea5y c\u00e1c v\u00ed d\u1ee5 nh\u01b0 sau:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ try-with-resource statement will auto close the connection.\n        try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {\n            preparedStatement.setString(1, user.getName());\n            preparedStatement.setString(2, user.getEmail());\n            preparedStatement.setString(3, user.getCountry());\n            System.out.println(preparedStatement);\n            preparedStatement.executeUpdate();\n        } catch (SQLException e) {\n            printSQLException(e);\n        }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Code k\u1ebft n\u1ed1i CSDL th\u01b0\u1eddng \u0111\u01b0\u1ee3c \u0111\u1ec3 trong <code>try()<\/code> (c\u00e1i n\u00e0y \u0111\u01b0\u1ee3c g\u1ecdi l\u00e0 try with resource) ch\u1ee9 kh\u00f4ng ph\u1ea3i trong <code>try(){}<\/code>, vi\u1ebft \u0111\u01b0\u1ee3c \u1edf \u0111\u00e2y kh\u00f4ng c\u1ea7n d\u00f9ng <strong>finally<\/strong> \u0111\u1ec3 \u0111\u00f3ng k\u1ebft n\u1ed1i l\u1ea1i.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> try (BufferedReader r = Files.newBufferedReader(path1);\n                BufferedWriter w = Files.newBufferedWriter(path2)) {\n              \/\/ protected code\n     }\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Trong \u0111o\u1ea1n code tr\u00ean c\u00f3 2 Resource l\u00e0 BufferedReader v\u00e0 BufferedWriter. Ch\u00fang ta c\u00f3 th\u1ec3 s\u1eed d\u1ee5ng nhi\u1ec1u Resource b\u00ean trong try, c\u00e1c Resource n\u00e0y s\u1ebd t\u1ef1 \u0111\u00f3ng khi ch\u01b0\u01a1ng tr\u00ecnh ho\u00e0n th\u00e0nh ho\u1eb7c khi c\u00f3 ngo\u1ea1i l\u1ec7 x\u1ea3y ra.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Tu\u1ef3 ch\u1ec9nh AutoCloseable.<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Ngo\u00e0i c\u00e1c class c\u00f3 s\u1eb5n trong Java, ch\u00fang ta c\u00f3 th\u1ec3 s\u1eed d\u1ee5ng try-with-resource v\u1edbi c\u00e1c class t\u1ef1 t\u1ea1o, b\u1eb1ng c\u00e1ch t\u1ea1o 1 class is a interface java.lang.AutoCloseable. Interface AutoCloseable l\u00e0 1 functional interface ch\u1ec9 c\u00f3 1 ph\u01b0\u01a1ng th\u1ee9c close.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/vukieuanh.com\/wp-content\/uploads\/2022\/02\/Screen-Shot-2022-02-09-at-11.20.10-1024x749.png\" alt=\"\" class=\"wp-image-718\"\/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Sau \u0111\u00e2y s\u1ebd l\u00e0 c\u00e1ch tu\u1ef3 ch\u1ec9nh 1 class v\u1edbi AutoCloseAble.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class DemoAutoCloseable implements AutoCloseable {\n    public void m1(){\n        System.out.println(\"M1 working ....\");\n    }\n    @Override\n    public void close() throws Exception {\n        System.out.println(\"Close\");\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">V\u00e0 \u0111\u00e2y l\u00e0 main<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static void main(String&#91;] args) throws Exception {\n        try(DemoAutoCloseable demoAutoCloseable = new DemoAutoCloseable()){\n            demoAutoCloseable.m1();\n        }\n    }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">K\u1ebft qu\u1ea3 c\u1ee7a main ch\u1ea1y \u0111\u01b0\u1ee3c nh\u01b0 sau:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>M1 working ....\nClose<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">C\u00f3 ngh\u0129a l\u00e0 ch\u01b0\u01a1ng tr\u00ecnh t\u1ef1 \u0111\u1ed9ng ch\u1ea1y ph\u01b0\u01a1ng th\u1ee9c close. Try-with -resource n\u00e0y kh\u00e1 m\u1ea1nh v\u00ec n\u00f3 \u0111\u1ea3m b\u1ea3o \u0111\u01b0\u1ee3c t\u1ea5t c\u1ea3 m\u1ecdi t\u00e0i nguy\u00ean \u0111\u1ec1u \u0111\u01b0\u1ee3c \u0111\u00f3ng d\u00f9 c\u00f3 b\u1ea5t k\u1ef3 chuy\u1ec7n g\u00ec x\u1ea3y ra -)))<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">M\u1ed9t v\u00e0i l\u01b0u \u00fd<\/h2>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<ul class=\"wp-block-list\"><li>Try-with-resource b\u1eaft bu\u1ed9c ph\u1ea3i d\u00f9ng v\u1edbi 1 is a c\u1ee7a AutoCloseable (Java s\u1ebd b\u00e1o l\u1ed7i compile lu\u00f4n)<\/li><li>Ph\u01b0\u01a1ng th\u1ee9c close c\u1ee7a AutoCloseable l\u00e0 ph\u01b0\u01a1ng th\u1ee9c throw Exception n\u00ean m\u00ecnh ph\u1ea3i handle khi s\u1eed d\u1ee5ng. <\/li><li>Tuy nhi\u00ean Java kh\u00f4ng khuy\u1ebfn kh\u00edch ch\u00fang ta throw Exception chung chung m\u00e0 n\u00ean c\u1ee5 th\u1ec3 Exception. <\/li><li>Ph\u01b0\u01a1ng th\u1ee9c close n\u00ean l\u00e0 1 ph\u01b0\u01a1ng th\u1ee9c idempotent (Ngh\u0129a l\u00e0 n\u00f3 c\u00f3 th\u1ec3 g\u1ecdi tho\u1ea3i m\u00e1i m\u00e0 ko l\u00e0m \u1ea3nh h\u01b0\u1edfng gi\u00e1 tr\u1ecb n\u00e0o)<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">V\u00ed d\u1ee5: <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Class ExampleOne \u0111\u01b0\u1ee3c khuy\u1ebfn kh\u00edch h\u01a1n so v\u1edbi Class ExampleTwo do throws 1 Exception c\u1ee5 th\u1ec3.<\/li><li>Ph\u01b0\u01a1ng th\u1ee9c close c\u1ee7a ExampleThree kh\u00f4ng \u0111\u1ea3m b\u1ea3o idempotent do m\u1ed7i l\u1ea7n g\u1ecdi n\u00f3 thay \u0111\u1ed5i gi\u00e1 tr\u1ecb c\u1ee7a bi\u1ebfn COUNT.<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>class ExampleOne implements AutoCloseable {\n    public void close() throws IllegalStateException {\n        throw new IllegalStateException(\"Cage door does not close\"); }\n}\nclass ExampleTwo implements AutoCloseable {\n    public void close() throws Exception {\n        throw new Exception(\"Cage door does not close\");\n    } }\nclass ExampleThree implements AutoCloseable {\n    static int COUNT = 0;\n    public void close() {\n        COUNT++; }\n}<\/code><\/pre>\n<\/div><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Exception b\u1ecb tri\u1ec7t ti\u00eau (Suppressed Exceptions)<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Trong tr\u01b0\u1eddng h\u1ee3p ph\u01b0\u01a1ng th\u1ee9c close x\u1ea3y ra Exception. V\u00ed d\u1ee5<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class JammedTurkeyCage implements AutoCloseable {\n    public void close() throws IllegalStateException {\n        throw new IllegalStateException(\"Cage door does not close\");\n    }\n\n    public static void main(String&#91;] args) {\n        try (JammedTurkeyCage t = new JammedTurkeyCage()) {\n            System.out.println(\"put turkeys in\");\n        } catch (IllegalStateException e) {\n            System.out.println(\"caught: \" + e.getMessage());\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">K\u1ebft qu\u1ea3 c\u1ee7a \u0111o\u1ea1n m\u00e3 tr\u00ean nh\u01b0 sau:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>put turkeys in\ncaught: Cage door does not close<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u0110o\u1ea1n m\u00e3 tr\u00ean ok ko l\u0103n t\u0103n g\u00ec n\u1eefa. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Trong tr\u01b0\u1eddng h\u1ee3p kh\u1ed1i try c\u0169ng l\u1ea1i n\u00e9m ra ngo\u1ea1i l\u1ec7. Sau phi\u00ean b\u1ea3n Java cung c\u1ea5p th\u00eam 1 c\u00e1ch \u0111\u1ec3 t\u00edch lu\u1ef9 c\u00e1c ngo\u1ea1i l\u1ec7 trong tr\u01b0\u1eddng h\u1ee3p c\u00e1c ngo\u1ea1i l\u1ec7 ch\u1ed3ng ch\u1ea5t l\u00ean nhau. C\u00f9ng theo d\u00f5i v\u00ed d\u1ee5 sau:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static void main(String&#91;] args) {\n        try (JammedTurkeyCage t = new JammedTurkeyCage()) {\n            throw new IllegalStateException(\"turkeys ran off\");\n        } catch (IllegalStateException e) {\n            System.out.println(\"caught: \" + e.getMessage());\n        }\n    }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">K\u1ebft qu\u1ea3 in ra nh\u01b0 sau:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>caught: turkeys ran off<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">C\u00f3 ngh\u0129a l\u00e0 ph\u1ea7n catch ch\u1ec9 b\u1eaft c\u1ee7a exception n\u00e9m ra trong try, c\u00f2n exception trong try-with-resource kh\u00f4ng th\u1ea5y \u0111\u00e2u -))).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">C\u00f9ng ti\u1ebfp t\u1ee5c xem v\u00ed d\u1ee5 sau<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static void main(String&#91;] args) {\n        try (JammedTurkeyCage t = new JammedTurkeyCage()) {\n            throw new IllegalStateException(\"turkeys ran off\");\n        } catch (IllegalStateException e) {\n            System.out.println(\"caught: \" + e.getMessage());\n            for (Throwable t: e.getSuppressed())\n                System.out.println(t.getMessage());\n        }\n    }<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/vukieuanh.com\/wp-content\/uploads\/2022\/02\/Screen-Shot-2022-02-10-at-21.55.16-1024x334.png\" alt=\"\" class=\"wp-image-730\"\/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">K\u1ebft qu\u1ea3 nh\u01b0 sau:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>caught: turkeys ran off\nCage door does not close<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Trong \u0111o\u1ea1n code n\u00e0y c\u00f3 ph\u1ea7n e.getSuppressed \u0111\u1ec3 l\u1ea5y ra nh\u1eefng Exception b\u1ecb tri\u1ec7t ti\u00eau. V\u1eady Java \u0111\u1ed1i x\u1eed th\u1ebf n\u00e0o v\u1edbi c\u00e1c Exception gi\u1ed1ng nhau ch\u1ed3ng ch\u00e9o l\u00ean nhau? Java coi ngo\u1ea1i l\u1ec7 \u0111\u1ea7u ti\u00ean l\u00e0 ngo\u1ea1i l\u1ec7 ch\u00ednh v\u00e0 c\u00e1c ngo\u1ea1i l\u1ec7 sau autoclose l\u00e0 ngo\u1ea1i l\u1ec7 b\u1ecb tri\u1ec7t ti\u00eau:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>D\u00f2ng 8 n\u00e9m ngo\u1ea1i l\u1ec7 ch\u00ednh.<\/li><li>Ngay t\u1ea1i d\u00f2ng 8 m\u1ec7nh \u0111\u1ec1 try k\u1ebft th\u00fac Java g\u1ecdi ph\u01b0\u01a1ng th\u1ee9c close.<\/li><li>Exception IllegalStateException \u0111c th\u00eam v\u00e0o ngo\u1ea1i l\u1ec7 b\u1ecb tri\u1ec7t ti\u00eau.<\/li><li>D\u00f2ng s\u1ed1 10 b\u1eaft ngo\u1ea1i l\u1ec7 ch\u00ednh<\/li><li>V\u00f2ng l\u1eb7p for l\u1eb7p c\u00e1c ngo\u1ea1i l\u1ec7 b\u1ecb tri\u1ec7t ti\u00eau.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Ti\u1ebfp t\u1ee5c t\u00ecm ti\u1ebfp ngo\u1ea1i l\u1ec7 trong v\u00ed d\u1ee5 ti\u1ebfp theo:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> public static void main(String&#91;] args) {\n        try (JammedTurkeyCage t = new JammedTurkeyCage()) {\n            throw new RuntimeException(\"turkeys ran off\");\n        } catch (IllegalStateException e) {\n            System.out.println(\"caught: \" + e.getMessage());\n        }\n    }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Trong try n\u00e9m ra m\u1ed9t ngo\u1ea1i l\u1ec7 Runtime<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">H\u1ebft r\u1ed3i.  Tham kh\u1ea3o t\u1eeb s\u00e1ch OCP ch\u01b0\u01a1ng 6.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Gi\u1edbi thi\u1ec7u T\u1eeb phi\u00ean b\u1ea3n Java 7, ch\u00fang ta c\u00f3 th\u1ec3 s\u1eed d\u1ee5ng t\u00ednh n\u0103ng try-with-resource v\u1edbi nh\u1eefng class c\u00f3 s\u1eb5n c\u1ee7a Java. Resource&nbsp;l\u00e0 m\u1ed9t \u0111\u1ed1i t\u01b0\u1ee3ng \u0111\u1ea1i di\u1ec7n cho t\u00e0i nguy\u00ean c\u1ea7n ph\u1ea3i \u0111\u01b0\u1ee3c \u0111\u00f3ng l\u1ea1i m\u1ed7i khi s\u1eed d\u1ee5ng n\u00f3. V\u00ed d\u1ee5 file, k\u1ebft n\u1ed1i CSDL. Trong JDBC, ta hay th\u1ea5y c\u00e1c v\u00ed [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-714","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/posts\/714","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/comments?post=714"}],"version-history":[{"count":13,"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/posts\/714\/revisions"}],"predecessor-version":[{"id":732,"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/posts\/714\/revisions\/732"}],"wp:attachment":[{"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/media?parent=714"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/categories?post=714"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/vukieuanh.net\/index.php\/wp-json\/wp\/v2\/tags?post=714"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}