javaautocloseable

Is it important to add AutoCloseable in java?


Is it important to implement AutoCloseable in java?

Would it make sense if I create a class which implements AutoCloseable extends a other class which doesn't implement it?

e.g

public class IGetClosed extends ICannotBeClosed implements AutoCloseable {...}

Solution

  • Is it important to implement autoCloseable in java?

    It is hard to tell it is important or not to implement the interface. But it is not required.

    Would it make sense if I create a class which implement AutoCloseable extends a other class which doesn't implement it?

    It is OK to do that. Nothing wrong.

    AutoCloseable was added from Java 7. It is designed to use with new try-with-resources statement (Java 7+)

    See two below classes providing the same functionality. One is not using AutoCloseable and the other is using AutoClosable:

    // Not use AutoClosable
    public class CloseableImpl {
        public void doSomething() throws Exception { // ... }
        public void close() throws Exception { // ...}
        
        public static void main(String[] args) {
            CloseableImpl impl = new CloseableImpl();
            try {
                impl.doSomething();
    
            } catch (Exception e) {
                // ex from doSomething
            } finally {
                try { //  impl.close() must be called explicitly
                    impl.close();
                } catch (Exception e) { }
            }
        }
    }
    
    // Use AutoCloseable 
    public class AutoCloseableImpl implements AutoCloseable {
        public void doSomething() throws Exception { // ... }
        public void close() throws Exception { // ...}
    
        public static void main(String[] args) {
            // impl.close() will be called implicitly
    
            try (AutoCloseableImpl impl = new AutoCloseableImpl()) {
                impl.doSomething();
            } catch (Exception e) {
              // ex from doSomething or close
            }
        }
    }
    

    As you see. Using AutoClosble will make the code shorter and cleaner.