Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 7 Automatic Resource Management JDBC (try-with-resources statement)

How to integrate the common JDBC idiom of creating/receiving a connection, querying the database and possibly processing the results with Java 7's automatic resource management, the try-with-resources statement? (Tutorial)

Before Java 7, the usual pattern was something like this:

Connection con = null; PreparedStatement prep = null;  try{     con = getConnection();     prep = prep.prepareStatement("Update ...");     ...     con.commit(); } catch (SQLException e){     con.rollback();      throw e; } finally{     if (prep != null)         prep.close();     if (con != null)         con.close(); } 

With Java 7 you can go for:

try(Connection con = getConnection(); PreparedStatement prep = con.prepareConnection("Update ..."){     ...    con.commit(); } 

This will close the Connection and the PreparedStatement, but what about the rollback? I cannot add a catch clause containing the rollback, because the connection is only available within the try block.

Do you still define the connection outside of the try block? What is the best practice here, especially if connection pooling is used?

like image 967
TPete Avatar asked Feb 13 '12 12:02

TPete


People also ask

What is the try-with-resources statement in Java?

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 with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.

Which one of the option is valid to close the resources automatically in Java 7?

automatic resource management or try-with-resources is a new exception handling mechanism that was introduced in Java 7, which automatically closes the resources used within the try-catch block.

How do you write to try-with-resources?

A resource is an object to be closed at the end of the program. As seen from the above syntax, we declare the try-with-resources statement by, declaring and instantiating the resource within the try clause. specifying and handling all exceptions that might be thrown while closing the resource.

How does Java 7 handle closing of resources?

Support for try-with-resources — introduced in Java 7 — allows us to declare resources to be used in a try block with the assurance that the resources will be closed after the execution of that block. The resources declared need to implement the AutoCloseable interface.

What is try with Resource Statements in Java?

Automatic Resource Management in Java | try with resource statements. Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management(ARM) using try-with-resources from Java 7 onwards.

What is automatic resource management in Java?

Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management (ARM) using try-with-resources from Java 7 onwards.

What is try-with-resources in Java 7?

This article presents the Java 7 answer to the automatic resource management problem in the form of a new language construct, proposed as part of Project Coin, called the try-with-resources statement. The typical Java application manipulates several types of resources such as files, streams, sockets, and database connections.

How to close resources automatically in Java 7?

In Java 7, a new try-with-resources approach is introduced, it helps to close resources automatically. try (open resources, one or more resources) { //... } //after try block, the resource will be closed automatically.


1 Answers

try(Connection con = getConnection()) {    try (PreparedStatement prep = con.prepareConnection("Update ...")) {        //prep.doSomething();        //...        //etc        con.commit();    } catch (SQLException e) {        //any other actions necessary on failure        con.rollback();        //consider a re-throw, throwing a wrapping exception, etc    } } 

According to the oracle documentation, you can combine a try-with-resources block with a regular try block. IMO, the above example captures the correct logic, which is:

  • Attempt to close the PreparedStatement if nothing goes wrong
  • If something goes wrong in the inner block, (no matter what is is) roll back the current transaction
  • Attempt to close the connection no matter what
  • If something goes wrong closing the connection, you can't rollback the transaction (as that's a method on the connection, which is now in indeterminate state), so don't try

In java 6 and earlier, I would do this with a triply nested set of try blocks (outer try-finally, middle try-catch, inner try-finally). ARM syntax does make this terser.

like image 133
Sean Reilly Avatar answered Sep 21 '22 18:09

Sean Reilly