Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

Java 7 : Try-with-resources - Close resources automatically with AutoCloseable interface

Every time we write code with FileInputStream,

BufferReader

  etc. we need to close those resource explicitly in finally block.

Now from Java 7, there are two interfaces included

Closeable

and

AutoCloseable

with single abstract method

close(),

  which enables implementing class to close resources aromatically after try block.

Lets see how it works.

Conventional way of using FileInputStream

File file = new File("C:\Document1.txt");
        InputStream fis = null;
        try
        {
            fis = new FileInputStream(file);
            System.out.println(file.getAbsolutePath());
            int readLocation;
            while ((readLocation = fis.read()) != -1) {
                System.out.print((char) readLocation);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

Now with using Try-with-Resource

try (InputStream fileInputStream = new FileInputStream(new File("C:\Document1.txt")))   {
            int readLocation;
            while ((readLocation = fileInputStream.read()) != -1) {
                System.out.print((char) readLocation);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

How it works:

Compare the changes. Initialization, of resource which needs to be close, happening with try and there is no finally block to close. FileInputStream implements Closeable which have following code in method

close()

.

 public void close() throws IOException {
        synchronized (closeLock) {
            if (closed) {
                return;
            }
            closed = true;
        }
        if (channel != null) {
            /*
             * Decrement the FD use count associated with the channel
             * The use count is incremented whenever a new channel
             * is obtained from this stream.
             */
           fd.decrementAndGetUseCount();
           channel.close();
        }

        /*
         * Decrement the FD use count associated with this stream
         */
        int useCount = fd.decrementAndGetUseCount();

        /*
         * If FileDescriptor is still in use by another stream, the finalizer
         * will not close it.
         */
        if ((useCount <= 0) || !isRunningFinalize()) {
            close0();
        }
    }

Note that you can still use

finally

block if you want.

Closeable vs AutoCloseable

Here is the code

public interface AutoCloseable {
 /**
     * Closes this resource, relinquishing any underlying resources.
     * This method is invoked automatically on objects managed by the
     * {@code try}-with-resources statement.
*/
    public void close() throws Exception;
}
public interface Closeable extends AutoCloseable {

    /**
     * Closes this stream and releases any system resources associated
     * with it. If the stream is already closed then invoking this
     * method has no effect.
     *
     * @throws IOException if an I/O error occurs
     */
    public void close() throws IOException; 
}

I hope it clears out when to use AutoCloseable and Closeable..

Oracle Page for Try-With-Resources

© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy