Archive

Posts Tagged ‘java 7 automatic resource management’

Java 7 Awesome Aspect-Automatic Resource Management

December 19, 2010 7 comments

Introduction:

In my previous article,” Java 7 Awesome Features” I had missed one of the greatest aspect of Java 7.That is nothing but “Automatic Resource Management”. This article deals with the same.

Managing Resource is one of the keen thing in development. Because if we don’t manage the resource effectively it will cause lot of issues like PermGen Space Error, TooManyConnections Error etc.

For avoid those problems Java 7 introduce the great aspect “Automatic Resource Management”. By this feature java can automatically manage the resources effectively. So java frees the developer from lots of overhead. Lets have a prolix look on this.

Syntax:


try(Resource 1;Resource 2;Resource 3….)

{

//block of statements

}

catch(Exception e)

{

//block of statements

}

Here is simple code snippet which shows you the typical try-catch-finally block. In the code we create the jdbc connection for access the data from database.


Connection connection = null;

Statement statement = null;

try

{

connection =    DriverManager.getConnection(“databaseurl”,”username(opt)”,”password(opt)”);

statement = connection.createStatemnet();

boolean executionStatus= statement.execute(“query”);

}

catch(Exception e)

{

//Block of code for handle the exception

e.printStacktrace();

}

finally

{

try

{

statement.close();

connection.close();

}

catch(Exception e)

{

//block of statements for handle exceptions.

}

}

In the above snippet, suppose we forget to close the statement and connection, what happened? May be after some operations (which also open the connection) “Too Many connection error” will occurred.

But java 7 keeps us in safe zone from those kinds of errors by mange the resource automatically. In java 7 we can write the above snippet like this,


Connection connection = null;

Statement statement = null;

try(connection =    DriverManager.getConnection(“databaseurl”,”username(opt)”,”password(opt)”);

statement = connection.createStatemnet())

{

boolean executionStatus= statement.execute(“query”);

}

catch(Exception e)

{

//block of statements for handles the exceptions

}

In the above snippet, there are no overheads like close the connections and statements properly. Java 7 can manage those things automatically for us.

Note:

Java 7 mange the resources which are sub interfaces and implementing classes of AutoCloseable.So we can pass the resources which are extends or implements the interface AutoCloseable.

That’s all folks, I think this article makes you bit more knowledgeable about java 7 awesome aspect “Automatic resource Management”, If you feel the same, please leave your footprints(comments) here. Joyous coding day…..