gpt4 book ai didi

java - DriverManager.deregisterDriver(driver) 是否关闭所有连接?

转载 作者:行者123 更新时间:2023-11-30 07:52:25 25 4
gpt4 key购买 nike

我需要在上下文被破坏时关闭所有 tomcat 连接池的数据源连接。 DriverManager.deregisterDriver(driver) 是否关闭所有连接?

Enumeration<Driver> enumDrivers = DriverManager.getDrivers();
while (enumDrivers.hasMoreElements()) {
Driver driver = enumDrivers.nextElement();
DriverManager.deregisterDriver(driver);
}

最佳答案

这是 JDK 8 上 DriverManager.deregisterDriver(Driver driver) 的代码:

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

请注意,它只是从列表 (registeredDrivers) 中删除 DriverInfo 实例。如果它找到与驱动程序关联的 DriverAction,它会调用 driverAction.deregister()。来自docs方法:

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.

因此在所有情况下,您都不应该指望这一点,除非您完全确定底层实现。但这会使您的应用程序与它过于耦合。

关于java - DriverManager.deregisterDriver(driver) 是否关闭所有连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45913376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com