Home > Blockchain >  Why does a Connection enclosed in try with resources not allow any operations?
Why does a Connection enclosed in try with resources not allow any operations?

Time:07-20

I want to use try with resources, though my program can not fulfill operations after connection is closed.

String conn = "jdbc:mysql://localhost:3306/test?&serverTimeZone=Europe/Moscow&useSSL=false&allowPublicKeyRetrieval=true";
try (Connection connection = DriverManager.getConnection( conn,"root","admin"))
   {
    return connection;
   } catch (SQLException e) {
  throw new RuntimeException(e);
}

My project is https://github.com/anatoliy19/1.1.3.git

CodePudding user response:

The resource allocated in the try-with-resources block is closed when you leave the block. So when you return the connection, that connection is closed. The reference to the connection is still valid though and will not be GCed until it is no longer referenced.

You can think of it this way. If the connection returned here was not closed, when would the compiler know that it should close it? The compiler can not know that.

You should use the connection inside that block or manage closing the connection yourself and not use try-with-resources.

CodePudding user response:

The try-with-resources statement ensures that each resource is closed at the end of this expression.

As per contract any object that:

implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable,

can be used as a resource.

The java.sql.Connection interface extends AutoClosable.

Therefore, an implementation of the close() method is guaranteed to be called automatically at runtime via the try-with-resources construction. Calling close() results in:

Closes this resource, relinquishing any underlying resources.

In case of a JDBC driver, communication with the database management system is "cut off“ in a normal and synchronous manner. Afterwards, the object you pass on (by returning it) is, practically speaking, useless.

  • Related