Skip to main content

(How) can I improve the resource handling code

Can you improve the resource handling code?

package com.javahowdoi.challengeq;

public class LockQ {
    public static class LockInner {
        public void acquire() {
            // acquire the resource
            //...
            // dummy print
            System.out.println("acquire");
        }
        public void release() {
            // resource release code
            //...
            //...
            // dummy print
            System.out.println("release");
        }
    }

    public static void main(String[] args) {
        LockInner li  = new LockInner();
        try {
            li.acquire();
        } finally {
            li.release();
        }
    }
}

Highlight the lines below to view the answer:

LockInner should implement AutoCloseable interface so that it can be used it in try with resources.  See demo code below

package com.javahowdoi.challengeq;

public class LockA {
    public static class LockInner implements AutoCloseable {
        public void acquire() {
            // acquire the resource
            //...
            // dummy print
            System.out.println("acquire");
        }

        @Override
        public void close() throws Exception {
            // resource release code
            //...
            //...
            // dummy print
            System.out.println("release");
        }
    }

    public static void main(String[] args) throws Exception {
        try(LockInner li  = new LockInner()) {
            li.acquire();
        }
    }
}

Comments