Java 7 language features - Try with Resources statement

Hi Friends,

Java has come up with really cool features in version 1.7.Code was named as Dolphin and released on July 28,2011.If you are interested in knowing history of all Java releases, you can go throw my earlier post History of java language.                                      




This is my first tutorial on Java 7 features where we will see one of the very cool feature included in Java 7 ,which is try with resources statement.

So What is resource 

When we develop an enterprise Java Application, our application need to interact with different kind of external resources like database, File System, remote System. To interact with these resources ,we will have in Java a corresponding Class/Object representing the resource to communicate with the resource. For example a physical file on the File System is represented by java.io.File.

Why Try With Resources was needed

So while interacting with many external resources, ideally a programmer should open a connection with resource, communicate with that resource and then close the connection. But that is in ideal World :)

In real world there are chances that programmer will forget to close the resource after opening it which can lead to unwanted objects which can not be collected by garbage collector and can lead to memory leaks.

Try With Resources Statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the program. Any object that implements java.lang.Closeable can be used as a resource. AutoCloseable interface provides following method which the classes which are implementing AutoCloseable needs to implement
void close() throws Exception;

Here are all SubInterfaces of AutoCloseable 
AsynchronousByteChannel, AsynchronousChannel, ByteChannel, CachedRowSet, CallableStatement, Channel, Clip, Closeable, Connection, DataLine, DirectoryStream<T>, FilteredRowSet, GatheringByteChannel, ImageInputStream,ImageOutputStream, InterruptibleChannel, JavaFileManager, JdbcRowSet, JMXConnector, JoinRowSet, Line, MidiDevice, MidiDeviceReceiver, MidiDeviceTransmitter, Mixer, MulticastChannel, NetworkChannel, ObjectInput, ObjectOutput,Port, PreparedStatement, ReadableByteChannel, Receiver, ResultSet, RMIConnection, RowSet, ScatteringByteChannel, SecureDirectoryStream<T>, SeekableByteChannel, Sequencer, SourceDataLine, StandardJavaFileManager,Statement, SyncResolver, Synthesizer, TargetDataLine, Transmitter, WatchService, WebRowSet, WritableByteChannel


Here are all Implementing Classes of AutoCloseable

AbstractInterruptibleChannel, AbstractSelectableChannel, AbstractSelector, AsynchronousFileChannel, AsynchronousServerSocketChannel, AsynchronousSocketChannel, AudioInputStream, BufferedInputStream, BufferedOutputStream,BufferedReader, BufferedWriter, ByteArrayInputStream, ByteArrayOutputStream, CharArrayReader, CharArrayWriter, CheckedInputStream, CheckedOutputStream, CipherInputStream, CipherOutputStream, DatagramChannel,DatagramSocket, DataInputStream, DataOutputStream, DeflaterInputStream, DeflaterOutputStream, DigestInputStream, DigestOutputStream, FileCacheImageInputStream, FileCacheImageOutputStream, FileChannel,FileImageInputStream, FileImageOutputStream, FileInputStream, FileLock, FileOutputStream, FileReader, FileSystem, FileWriter, FilterInputStream, FilterOutputStream, FilterReader, FilterWriter, Formatter, ForwardingJavaFileManager,GZIPInputStream, GZIPOutputStream, ImageInputStreamImpl, ImageOutputStreamImpl, InflaterInputStream, InflaterOutputStream, InputStream, InputStream, InputStream, InputStreamReader, JarFile, JarInputStream, JarOutputStream,LineNumberInputStream, LineNumberReader, LogStream, MemoryCacheImageInputStream, MemoryCacheImageOutputStream, MLet, MulticastSocket, ObjectInputStream, ObjectOutputStream, OutputStream, OutputStream, OutputStream,OutputStreamWriter, Pipe.SinkChannel, Pipe.SourceChannel, PipedInputStream, PipedOutputStream, PipedReader, PipedWriter, PrintStream, PrintWriter, PrivateMLet, ProgressMonitorInputStream, PushbackInputStream,PushbackReader, RandomAccessFile, Reader, RMIConnectionImpl, RMIConnectionImpl_Stub, RMIConnector, RMIIIOPServerImpl, RMIJRMPServerImpl, RMIServerImpl, Scanner, SelectableChannel, Selector, SequenceInputStream,ServerSocket, ServerSocketChannel, Socket, SocketChannel, SSLServerSocket, SSLSocket, StringBufferInputStream, StringReader, StringWriter, URLClassLoader, Writer, XMLDecoder, XMLEncoder, ZipFile, ZipInputStream,ZipOutputStream

Before Java 7,if we wanted to close the resources we were writing code for that in finally block as below and there were great chances that a programmer will forget to close the opened resource.
package com.blogspot.javasolutionsguide;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TryWithFinally {
 public static void main(String[] args) {
  try {
   String line = readFirstLine("C:/Users/Gaurav/test.txt");
   System.out.println("Line is :"+line);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 static String readFirstLine(String path) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
      return br.readLine();
    } finally {
      if (br != null)
       br.close();
    }
  }
}

So here basically we are instantiating BufferedReader before try statement ,using BufferedReader to read first line from test.txt file  and then in finally block we are closing the BufferedReader.

How we will do same stuff in Java 7, Let us see.
package com.blogspot.javasolutionsguide;                                                                                                                         import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TryWithResources {
 public static void main(String[] args) {
  try {
   String line = readFirstLine("C:/Users/Gaurav/test.txt");
   System.out.println("Line is :"+line);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 static String readFirstLine(String path) throws IOException {
  
    try(BufferedReader br = new BufferedReader(new FileReader(path))) {
      return br.readLine();
    }
 }
}
Here resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly, as close method will be called automatically after try block has completed (as a result of method BufferedReader.readLine throwing an IOException).

Hope this was helpful. Any suggestions, questions on the post are welcome.