简体   繁体   English

如何从另一个线程强制关闭JDBC连接?

[英]How to force close JDBC connection from another thread?

I have two threads in java application. 我在Java应用程序中有两个线程。 The first thread runs the JDBC connection logic. 第一个线程运行JDBC连接逻辑。 The second one is listening to user's command. 第二个是监听用户的命令。

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

How to forcefully and abruptly stop the connection ? 如何强制和突然停止连接?

You could try calling c.close() in the 2nd thread, but: 您可以尝试在第二个线程中调用c.close() ,但是:

  • JDBC connection objects are not thread-safe 1 , so the Java-side behavior is unspecified. JDBC连接对象不是线程安全的1 ,因此未指定Java端的行为。

  • AFAIK, the JDBC spec doesn't say what will happen on the database server if a database connection is closed while a request is in progress. AFAIK,JDBC规范没有说明如果在进行请求时关闭数据库连接,数据库服务器上会发生什么。 It is not clear if the request is terminated immediately or a bit later (with a transaction rollback or not). 目前尚不清楚请求是立即终止还是稍后终止(是否具有事务回滚)。

So my advice would be don't do this. 所以我的建议是不要这样做。 Find another way to do what you are trying to do. 寻找另一种方法来做您想做的事情。

(If you want advice on other ways, tell us the real problem you are trying to solve here rather than your roadblock with your attempted solution to the problem.) (如果您需要其他方法的建议,请告诉我们您正在尝试解决的实际问题 ,而不是尝试解决问题的障碍。)


1 - More precisely, they are not required to be thread-safe by the JDBC spec. 1-更准确地说,JDBC规范不要求它们是线程安全的。 They might actually be (sufficiently) thread-safe in some driver implementations, but ... only if the vendor docs say so. 在某些驱动程序实现中,它们实际上可能(足够)是线程安全的,但是……仅在供应商文档中这样说。 From various sources, at least Oracle DB and Derby support multiple threads sharing a logical JDBC connection, though they seem to support different models. 尽管它们似乎支持不同的模型,但从各种来源来看,至少Oracle DB和Derby支持共享逻辑JDBC连接的多个线程。

I don't think you can this way. 我认为您不能这样。 But you can exit the whole JVM forcely:) 但是您可以强制退出整个JVM :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM