1 /* @test /nodynamiccopyright/ 2 * @bug 7196163 3 * @summary Verify that variables can be used as operands to try-with-resources 4 * @compile/fail/ref=TwrForVariable1.out -source 8 -XDrawDiagnostics -Xlint:-options TwrForVariable1.java 5 * @compile TwrForVariable1.java 6 * @run main TwrForVariable1 7 */ 8 public class TwrForVariable1 implements AutoCloseable { 9 private static int closeCount = 0; 10 public static void main(String... args) { 11 TwrForVariable1 v = new TwrForVariable1(); 12 13 try (v) { 14 assertCloseCount(0); 15 } 16 try (/**@deprecated*/v) { 17 assertCloseCount(1); 18 } 19 try (v.finalWrapper.finalField) { 20 assertCloseCount(2); 21 } catch (Exception ex) { 22 } 23 try (new TwrForVariable1() { }.finalWrapper.finalField) { 24 assertCloseCount(3); 25 } catch (Exception ex) { 26 } 27 try ((args.length > 0 ? v : new TwrForVariable1()).finalWrapper.finalField) { 28 assertCloseCount(4); 29 } catch (Exception ex) { 30 } 31 try { 32 throw new CloseableException(); 33 } catch (CloseableException ex) { 34 try (ex) { 35 assertCloseCount(5); 36 } 37 } 38 39 assertCloseCount(6); 40 41 // null test cases 42 TwrForVariable1 n = null; 43 44 try (n) { 45 } 46 try (n) { 47 throw new Exception(); 48 } catch (Exception e) { 49 } 50 51 assertCloseCount(6); 52 53 // initialization exception 54 TwrForVariable1 i1 = new TwrForVariable1(); 55 try (i1; TwrForVariable1 i2 = new TwrForVariable1(true)) { 56 } catch (Exception e) { 57 } 58 59 assertCloseCount(7); 60 61 // multiple closures 62 TwrForVariable1 m1 = new TwrForVariable1(); 63 try (m1; TwrForVariable1 m2 = m1; TwrForVariable1 m3 = m2;) { 64 } 65 66 assertCloseCount(10); 67 } 68 69 static void assertCloseCount(int expectedCloseCount) { 70 if (closeCount != expectedCloseCount) 71 throw new RuntimeException("bad closeCount: " + closeCount + 72 "; expected: " + expectedCloseCount); 73 } 74 75 public void close() { 76 closeCount++; 77 } 78 79 final FinalWrapper finalWrapper = new FinalWrapper(); 80 81 static class FinalWrapper { 82 public final AutoCloseable finalField = new AutoCloseable() { 83 @Override 84 public void close() throws Exception { 85 closeCount++; 86 } 87 }; 88 } 89 90 static class CloseableException extends Exception implements AutoCloseable { 91 @Override 92 public void close() { 93 closeCount++; 94 } 95 } 96 97 public TwrForVariable1(boolean throwException) { 98 if (throwException) 99 throw new RuntimeException("Initialization exception"); 100 } 101 102 public TwrForVariable1() { 103 this(false); 104 } 105 }