-3

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

can multiple threads use a same java.sql.Connection to send queries to a database at the same time? all the threads will use the connection at the same time.

if the connection is obtained from a singleton class, will the above case be possible still?

Community
  • 1
  • 1
Ranjan Sarma
  • 1,565
  • 5
  • 22
  • 36

2 Answers2

2

Yes, it's possible, but I would recommend that you implement some connection pooling - c3p0 is quite popular option.

1615903
  • 32,635
  • 12
  • 70
  • 99
1

No, java.sql.Connection is not thread safe. Imagine one thread issuing a command, while another command executes rollback. The previous command would be rolled back even if it would be perfectly valid. Or one thread executing a command while the other closes the connection.

However! There is no problem in creating multiple connections! SQL servers are designed to handle a large number of asynchronous connections. Instead of reinventing the wheel and synchronizing database access in the application, use the synchronization mechanism in the databse itself.

Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48