Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreaded JDBC

Tags:

Architecturally what is the best way to handle JDBC with multiple threads? I have many threads concurrently accessing the database. With a single connection and statement I get the following error message:

org.postgresql.util.PSQLException: This ResultSet is closed.

Should I use multiple connections, multiple statements or is there a better method? My preliminary thought was to use one statement per thread which would guarantee a single result set per statement.

like image 902
deltanovember Avatar asked Jul 25 '09 14:07

deltanovember


2 Answers

You should use one connection per task. If you use connection pooling you can't use prepared statements prepared by some other connection. All objects created by connection (ResultSet, PreparedStatements) are invalid for use after connection returned to pool.

So, it's alike

public void getSomeData() {
  Connection conn = datasource.getConnection();
  PreparedStatement st;
  try {
    st = conn.prepareStatement(...);
    st.execute();
  } finally {
    close(st);
    close(conn);
  }
}

So in this case all your DAO objects take not Connection, but DataSource object (java.sql.DataSource) which is poolable connection factory indeed. And in each method you first of all get connection, do all your work and close connection. You should return connection to pool as fast as possible. After connection returned it may not be physically closed, but reinitialized (all active transactions closed, all session variables destroyed etc.)

like image 134
Denis Bazhenov Avatar answered Dec 30 '22 19:12

Denis Bazhenov


Yes, use multiple connections with a connection pool. Open the connection for just long enough to do what you need, then close it as soon as you're done. Let the connection pool take care of the "physical" connection management for efficiency.

like image 29
Jon Skeet Avatar answered Dec 30 '22 19:12

Jon Skeet