Saturday, February 1, 2014

Automatic Resource Management in Java 7

Automatic Resource Management in Java 7

Generally FileInputStreams, FileOutputStreams, Connections etc are closed in the finally block.

try
{
    FileStream = new FileOutputStream ("test.txt");

    <some code>
}
catch (IOException exp)
{
   exp.printStackTrace();
}
finally
{
    try
    {
        FileStream.close();
    }
    catch (IOException exp)
    {
        <Some log>
    }
}


In Java 7, the resources are managed automatically.
We need to declare the resources in try block.
These resources now implement java.lang.AutoCloseable interface.

New code in Java 7:

try (FileOutputStream FileStream = new FileOutputStream ("test.txt"))
{
    <some code>
}
catch (IOException exp)
{
    <Some log>
}

If you have more than one resources, use them in the same try


try
(
    FileOutputStream FileStream = new FileOutputStream ("test.txt");
    Connection conn = new Connection();
)
{
    <code>
}


java.io.Closeable interface (Parent is AutoCloseable) has a close() method which is called by the JVM
when the control comes out of the try block.

No comments:

Post a Comment