Reuse or not to reuse connections off a connection pool

时间:2015-05-04 19:45:23

标签: java-ee connection-pooling

Lets say I am "reusing" connections like below in a multithreaded environment (details of exception handling and closing of resources are ommitted for the sake of brevity):

public contractMethod(){
  Connection conn = getConnectionFromJndiDSBackedByAPool();
  methodA(conn);
  // close conn
}

private methodA(Connection conn) {
  // do lots of things with the conn
  // close statements & resultsets
  methodB(conn);
}

private methodB(Connection conn) {
  // do lots of things with the conn
  // close statements & resultsets
}

Does the above approach perform better(and scalable) than to have each of the above methods to get(/open) the connections, do their works and close the connections(and other associated resources, of course) by themselves?

1 个答案:

答案 0 :(得分:1)

That's not your biggest issue. If you have a pool of already connected sessions, all ready to go, the performance gain you're likely going to get by passing the connection from methodA to methodB is not going to come up in the biggest win for quite a while. I would guess that the queries themselves would take the majority of the time.

Some databases will 'invalidate' the transaction you're in if an exception occurs, this means all further attempts to do things in that transaction will fail. Odds are you want this functionality if you're servicing the same public contractMethod, regardless of what private methods you're calling. Also, if you were to go the "fetch another connection" route per private method, your error handling becomes much more complex if there is no connection available for methodB to do its work.

Omitted from this answer is the fact that there are dozens of frameworks which hide this all from you and let you focus on solving problems, but I'm assuming you know this. :-)