try-with-resource / AMD ( automatic resource management)

try-with-resource / AMD ( automatic resource management)

A *resource* is as an object that must be closed manually,
such as a, OutputStream, Reader, Writer, Formatter;
java.nio.Channel;; java.sql.Connection, Statement, ResultSet,
or java.awt.Graphics.

The *automatic resource management statement* is a form of the try statement
that declares one or more resources. The scope of these resource
declarations is limited to the statement. When the statement completes,
whether normally or abruptly, all of its resources are closed automatically.


SIMPLE EXAMPLE: Here is a static method to read the first line of a file,
demonstrating the minimal (nearly) correct code to release a single resource
  static String readFirstLineFromFile(String path) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader(path));

        try {

            return br.readLine();

        } finally {


Unfortunately, if the readLine and close invocations both throw exceptions, the latter exception supplants the former. The only practical way around this today would to be to ignore any exception thrown by the close invocation. While this might be reasonable in the case of a Reader or InputStream, it would be disastrous for a Writer or OutputStream. Here’s how it would look with an automatic resource management statement:
    static String readFirstLineFromFile2(String path) throws IOException {

      try (BufferedReader br = new BufferedReader(new FileReader(path)) {

            return br.readLine();


You may declare one or more resources in a try-with-resources statement. like
   try ( zf = new; writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset) 
The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:
 public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

  try (Statement stmt = con.createStatement()){

      ResultSet rs = stmt.executeQuery(query);

      while ( {
        String coffeeName = rs.getString("COF_NAME");
        int supplierID = rs.getInt("SUP_ID");
        float price = rs.getFloat("PRICE");
        int sales = rs.getInt("SALES");
        int total = rs.getInt("TOTAL");
        System.out.println(coffeeName + ", " + supplierID + ", " + price +
                           ", " + sales + ", " + total);

    } catch (SQLException e) {
The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API. Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
Advantage : The automatic resource management statement obviates the need for manual resource termination, which has proven ugly and error prone. It could emit the code to suppress the uninteresting(second) exception in favor of the interesting(first) one with no effort on the part of the programmer, and no loss to the clarity of the program. Like the for-each statement(introduced in java 1.5), the automatic resource management statement is a small piece of syntactic sugar with a very high power-to-weight ratio.
 Disadvantage: Like all syntactic sugar, this construct removes a bit of java's "what you see is what you get" character ("transparency").

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...