0

I recently learned about Java's Try-with-Resources for autoclosable resources. I was rewriting a JSP to use the Try-with-Resources instead of a Try-Catch. When I took out the database driver's instantiation, the code still worked. How is that possible?

I am using Apache Tomcat, and think it must be something special Tomcat is doing, because in a regular Java class the driver.newInstance() must be in a try-catch block. In Tomcat, I removed it completely, and everything still worked like normal.

I went from this:

try{
    // Set up the connection
    Class.forName(driverName).newInstance();
    connection = DriverManager.getConnection(connectionURL, name, password);
    ...more stuff
}

to this:

try(Connection con = DriverManager.getConnection(connectionURL, name, password)){
    ...more stuff
}

Why does this work?

jabe
  • 784
  • 2
  • 15
  • 33
  • 2
    Since the implementation of the [ServiceLoader](http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html) in Java 6, any Java 6 compatible JDBC driver Jar file can auto-register with the `DriverManager`, making the `driver.newInstance()` unnecessary. It's Java, not Tomcat, doing this. – Andreas May 06 '16 at 23:14
  • What would happen if two separate JDBC drivers auto-registered with the `DriverManger`? How would the driver manager know which driver to use when `DriverManager.getConnection(...)` is called? – jabe Jul 14 '16 at 15:52
  • Are you asking about two difference versions of the *same* driver, or two difference drivers? You can have many drivers registered. The URL will be used to find the matching driver. – Andreas Jul 14 '16 at 15:57
  • Thanks for the explanation! – jabe Jul 14 '16 at 16:26

0 Answers0