我在 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 端行为。
AFAIK,JDBC 规范没有说明如果在请求正在进行时关闭数据库连接,数据库服务器上会发生什么。不清楚请求是立即终止还是稍后终止(是否有事务回滚)。
所以我的建议是不要这样做。寻找另一种方式来做你想做的事情。
(如果您需要其他方式的建议,请告诉我们您在此处尝试解决的真正问题,而不是您尝试解决问题的障碍。)
1 - 更准确地说,JDBC 规范不要求它们是线程安全的。在某些驱动程序实现中,它们实际上可能是(足够)线程安全的,但是......只有当供应商文档这样说时。从各种来源来看,至少 Oracle DB 和 Derby 支持多个线程共享一个逻辑 JDBC 连接,尽管它们似乎支持不同的模型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句