2

I have a servlet where I get a Connection object which is then handed to two worker threads for various activities. I now need to add a transaction on one thread.

If I start a transaction like this: connection.setAutoCommit(false);

would that impact both threads? I think it would.

Do I have to get a separate connection of each thread?

Thanks

1
  • you can not practically share a connection unless clearly stated in the JDBC driver manual. Commented Feb 24, 2011 at 21:19

1 Answer 1

1

I think what you are doing is very bad practice. You can't share a JDBC connection among threads.

If you are running under an application server (like TOMCAT/JBoss/WebSphere/WebLogic) use a proper DataSource to get your connections as you need them.

Look at your Application Server documentation to get information on how to do that.

You will have something like this in your 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 */ } } 

Similarly, your worker threads will have something like:

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 */ } } 

Eventually, you could set auto commit to whatever you need on separate connection objects.

Sign up to request clarification or add additional context in comments.

1 Comment

You're absolutely right. I hadn't considered the implications of sharing the connection, so I'm adjusting each thread to acquire it's own connection.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.