Is DriverManager.deregisterDriver(driver) closes all connections?

1k views Asked by At

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);
}
1

There are 1 answers

0
M A On BEST ANSWER

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.