2

私は、さまざまなアクティビティのために2つのワーカースレッドに渡されるConnectionオブジェクトを取得するサーブレットを持っています。ここで、1つのスレッドにトランザクションを追加する必要があります。

次のようなトランザクションを開始した場合:connection.setAutoCommit(false);

それは両方のスレッドに影響しますか?そうだと思います。

各スレッドの個別の接続を取得する必要がありますか?

ありがとう

4

1 に答える 1

1

あなたがしていることは非常に悪い習慣だと思います。スレッド間でJDBC接続を共有することはできません。

アプリケーションサーバー(TOMCAT / JBoss / WebSphere / WebLogicなど)で実行している場合は、適切なデータソースを使用して、必要に応じて接続を取得します。

その方法については、アプリケーションサーバーのドキュメントを参照してください。

サーブレットには次のようなものがあります。

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個別の接続オブジェクトで必要なものに設定できます。

于 2011-02-24T21:14:56.743 に答える