1

Possible Duplicate:
Is java.sql.Connection thread safe?

I have gone through some tutorials.
They said to close the database connection through finally block.
But I have a question on my mind:

Think about a scenario where two threads are actively reading on one connection and one thread finishes his work and closes the connection. So what happens to the other?

Is the second thread able to complete his task?

Please let me know if my question is not valid and please let me know the best solution.

Community
  • 1
  • 1
Jasa
  • 41
  • 4

1 Answers1

5

Yes, a finally block is the correct way to close a Connection and other JDBC resources.

You should avoid sharing such objects between threads; while they are probably thread-safe, they are not intended to be used in this way. One JDBC specification says, "In practice we expect that most of the JDBC objects will only be accessed in a single threaded way."

If you have multiple threads using the same database, create a pool of connections, and allow each thread exclusive access to a Connection and its subsidiary resources.

erickson
  • 265,237
  • 58
  • 395
  • 493