2

I need to close all tomcat connection pool's datasource connections while context destroyed. Is DriverManager.deregisterDriver(driver) closes all connections?

Enumeration<Driver> enumDrivers = DriverManager.getDrivers();
while (enumDrivers.hasMoreElements()) {
   Driver driver = enumDrivers.nextElement();
   DriverManager.deregisterDriver(driver);
}
nikli
  • 2,281
  • 2
  • 24
  • 38
  • It probably doesn't – Maurice Perry Aug 28 '17 at 07:05
  • 1
    No it doesn't. Nothing about it in the [Javadoc](https://docs.oracle.com/javase/8/docs/api/java/sql/DriverManager.html). If the connection pool is part of the context, it will be destroyed with the context, and it should release all its idle connections in the process. You don't have to do anything about this. In any case if you're using a connection pool you are using a `DataSource`, not a `DriverManager`. – user207421 Aug 28 '17 at 07:27
  • You should never call `deregisterDriver`, it is for JDBC drivers to unregister themselves, not - at least not typically - for application code. – Mark Rotteveel Aug 28 '17 at 08:47

1 Answers1

3

Here is the code of DriverManager.deregisterDriver(Driver driver) on JDK 8:

DriverInfo aDriver = new DriverInfo(driver, null);
if(registeredDrivers.contains(aDriver)) {
    if (isDriverAllowed(driver, Reflection.getCallerClass())) {
        DriverInfo di = registeredDrivers.get(registeredDrivers.indexOf(aDriver));
        // If a DriverAction was specified, Call it to notify the
        // driver that it has been deregistered
        if(di.action() != null) {
           di.action().deregister();
        }
        registeredDrivers.remove(aDriver);
    } else {
        // If the caller does not have permission to load the driver then
        // throw a SecurityException.
        throw new SecurityException();
    }

Note that it just removes the DriverInfo instance from a list (registeredDrivers). In case it finds a DriverAction associated with the driver, it calls driverAction.deregister(). From the docs of the method:

The deregister method is intended only to be used by JDBC Drivers and not by applications. JDBC drivers are recommended to not implement DriverAction in a public class. If there are active connections to the database at the time that the deregister method is called, it is implementation specific as to whether the connections are closed or allowed to continue. Once this method is called, it is implementation specific as to whether the driver may limit the ability to create new connections to the database, invoke other Driver methods or throw a SQLException. Consult your JDBC driver's documentation for additional information on its behavior.

So in all cases, you shouldn't count on this, unless you're absolutely sure of the underlying implementation. But this would render your application too coupled with it.

M A
  • 71,713
  • 13
  • 134
  • 174