[英]How to force close JDBC connection from another thread?
我在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連接的多個線程。
我認為您不能這樣。 但是您可以強制退出整個JVM :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.