Why close method of class that implements Autoclosable interface is called first than Sql connection close?

232 Views Asked by At

I found solution to rollback transaction when commit fails and It works perfectly. But could you explain why Autorollback object close method is called first than connection close?

Autorollback class :

public class AutoRollback implements AutoCloseable {
    private Connection conn;
    private boolean committed;
    public AutoRollback(Connection conn){
        this.conn = conn;
    }
    public void commit() throws SQLException {
        conn.commit();
        committed = true;
    }
    @Override
    public void close() throws SQLException {
        if(!committed) {
            conn.rollback();
        }
    }
}

example of service method that use Autorollback:

try(Connection connection = MySQLDAOFactory.getConnection();
            AutoRollback autoRollback = new AutoRollback(connection)){
            result =  carDao.insertCar(connection,car);
            autoRollback.commit();
        } catch (SQLException | NamingException | MySQLEXContainer.MySQLDBExecutionException throwables) {
            throw new ApplicationEXContainer.ApplicationCanNotChangeException(throwables.getMessage(),throwables);
        }

Why does Autorollback's close method works?If connection is closed how can it call rollback method?So the only explanation is autorollback close method is called earlier thah connection close, but why?

1

There are 1 best solutions below

1
On BEST ANSWER

Because that's how JLS says it has to work:

A try-with-resources statement is parameterized with variables (known as resources) that are initialized before execution of the try block and closed automatically, in the reverse order from which they were initialized, after execution of the try block.

Source