我在java应用程序中有两个线程。第一个线程运行 JDBC 连接逻辑。第二个是听用户的命令。
public static void main ...
private Connection c; // this is JDBC connection visible to both Thread 1 and 2
Thread thread1 = new Thread(new Runnable() {
public void run() {
// logic to execute SQL statements on Connection c
}
);
Thread thread2 = new Thread(new Runnable() {
public void run() {
// Here i try to execute connection close on user's demand.
c.close();
// this command executes with no error,
// but the connection doesnt close immediately.
// The SQL statements in thread 1 somehow waits to finish,
// and only then will the connection stop.
// How to forcefully and abruptly stop the connection ?
}
);
如何强制、突然停止连接?
最佳答案
您可以尝试在第二个线程中调用c.close()
,但是:
JDBC 连接对象不是线程安全的1,因此 Java 端行为未指定。
据我所知,JDBC 规范没有说明如果在请求正在进行时数据库连接关闭,数据库服务器上会发生什么。目前尚不清楚请求是立即终止还是稍后终止(是否有事务回滚)。
所以我的建议是不要这样做。寻找另一种方法来完成您想做的事情。
(如果您需要其他方法的建议,请告诉我们您正在尝试解决的真正问题,而不是您尝试解决该问题的障碍。)
<小时/>1 - 更准确地说,JDBC 规范不要求它们是线程安全的。在某些驱动程序实现中,它们实际上可能是(足够)线程安全的,但是......只有在供应商文档这么说的情况下。从各种来源来看,至少 Oracle DB 和 Derby 支持共享逻辑 JDBC 连接的多个线程,尽管它们似乎支持不同的模型。
关于java - 如何从另一个线程强制关闭 JDBC 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56282843/