0

I am calling my db connection method inside every single thread (using ExecutorService for fixed thread pooling) but if I am not using syncrhonized on the getConnection method then it is giving me error that

the connection has been closed

I am new to multi-threading so I read the Oracle document for DriverManager.getConnection() and it says that

"The DriverManager.getConnection() method returns a new Java Connection object every time you call it. Note that although the method is not creating a new physical connection (only a single implicit connection is used), it is returning a new object."

If I am already passing new Connection object in each worker thread then how come connection is getting closed.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You shouldn't be sharing a single connection with different threads. That is trouble waiting to happen (like other threads closing the connection, calling rollback etc. etc.). – M. Deinum May 14 '20 at 07:14
  • @M. Deinum i am calling new connection object in each Task that the threads are going to perform. – Manish Kumar May 14 '20 at 07:30
  • 1
    Then your question doesn't make sense (as that points to sharing one). Also **which** `getConnection` method are you using the `DriverManager` or a `DataSource`. Also you state you are passing in the connection, why? If it itakes to long for anything to happen, the connection mightb e automatically closed. The thread should obtain a connection itself. – M. Deinum May 14 '20 at 07:37
  • Time to read about [connection pooling](https://stackoverflow.com/questions/2835090/how-to-establish-a-connection-pool-in-jdbc). – rkosegi May 14 '20 at 07:46
  • @M. Deinum executor.execute(new Technology(hashmap,userservice,logger)) In this Runnable class technology i have called getconnection method (DriverManager) Just want to understand how the connection is getting closed when i have called the connection method inside each task. Just want to understand. – Manish Kumar May 14 '20 at 09:58
  • If you call it in the constructor it might be to soon. As it gets used in the `run` method which could take a while before executing (or actually using the connection) which can lead to a forcefully closed connection. ALso please don't add code/config etc as comments as those are unreadable! Instead edit your question and add the additional information. – M. Deinum May 14 '20 at 10:02
  • Consider including the code in the question - nobody knows what you are actually doing. – vsfDawg May 14 '20 at 15:44

0 Answers0