File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Filter options
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Original file line number Diff line number Diff line change
1
+ import java .util .concurrent .TimeUnit ;
2
+
3
+ /**
4
+ * TryWithResources
5
+ */
6
+ class SimpleResouce implements AutoCloseable {
7
+ private final String name ;
8
+
9
+ public SimpleResouce (String name ) {
10
+ this .name = name ;
11
+ }
12
+
13
+ public String doWork (String context ) {
14
+ try {
15
+ TimeUnit .SECONDS .sleep (2 );
16
+ } catch (InterruptedException ie ) {
17
+ throw new RuntimeException (ie );
18
+ }
19
+ return "Work Done for " + context ;
20
+ }
21
+
22
+ @ Override
23
+ public void close () {
24
+ System .out .println ("Resource " + name + " closed" );
25
+ }
26
+ }
27
+
28
+ public class TryWithResources {
29
+ public static void main (String [] args ) {
30
+ // Before
31
+ try (SimpleResouce res = new SimpleResouce ("insideTryWithResource" )){
32
+ String workResponse = res .doWork ("old style try with resources" );
33
+ System .out .println (workResponse );
34
+ }
35
+
36
+
37
+ // Java 9
38
+ SimpleResouce resource = new SimpleResouce ("OutsideTryWithResource" );
39
+ try (resource ) {
40
+ String workResponse = resource .doWork ("yay! java 9" );
41
+ System .out .println (workResponse );
42
+ }
43
+
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments