2011-02-24 50 views
2

我有一個servlet,我得到一個Connection對象,然後交給兩個工作線程進行各種活動。我現在需要在一個線程上添加一個事務。跨線程共享連接的JDBC自動提交

如果我開始這樣一個事務: connection.setAutoCommit(false);

會影響兩個線程嗎?我認爲會的。

我必須得到每個線程的單獨連接嗎?

感謝

+0

除非在JDBC驅動程序手冊中明確聲明,否則實際上不能共享連接。 – bestsss 2011-02-24 21:19:05

回答

1

我覺得你在做什麼是非常不好的做法。您不能在線程之間共享JDBC連接。

如果您正在應用程序服務器(如TOMCAT/JBoss/WebSphere/WebLogic)下運行,請根據需要使用適當的DataSource來獲取連接。

查看您的Application Server文檔以獲取有關如何執行此操作的信息。

你有這樣的事情在你的servlet:

public void doGet(HttpServletRequest req, HttpServletResponse resp) 
{ 
    Connection c = null; 
    try { 
     c = ...; /* preferred way of getting a connection in your AppServer 
     // do what you need with your JDBC connection 
    } catch (Exception e) { 
     // handle errors 
    } finally { 
     c.close(); /* you will need another TRY/CATCH here */ 
    } 
} 

同樣,你的工作線程會碰到這樣的:

public void run() 
{ 
    Connection c = null; 
    try { 
     c = ...; /* preferred way of getting a connection in your AppServer 
     // do what you need with your JDBC connection 
    } catch (Exception e) { 
     // handle errors 
    } finally { 
     c.close(); /* you will need another TRY/CATCH here */ 
    } 
} 

最終,你可以設置auto commit到任何你需要在不同的連接對象。

+1

你是對的。我沒有考慮共享連接的影響,所以我正在調整每個線程以獲取它自己的連接。 – 2011-02-25 14:17:16