Reputation: 3574
I am writing an application in which one thread will have a permanent connection to a MySQL database using JDBC, and no other thread will ever use this connection.
My idea is something like this:
import java.sql.Connection;
public class ConHolder {
private Connection con;
public Connection getConnection(int checkTimeout) {
if(!con.isValid(checkTimeout)) {
con.close();
con = createNewConnection();
}
return con;
}
private Connection createNewConnection() {
return /* a newly created connection */;
}
}
Is this fine? Or is there a need for an actual connection pool?
Upvotes: 0
Views: 1485
Reputation: 719238
I think it is OK, more or less. The only possible issues are:
isValid
wasn't available prior to Java 6, and
there is still a potential failure mode where the connection goes bad between the application calling isValid
and trying to use the connection to do something that matters1.
1 - Note that you can get the same failure mode with a typical connection pool. The only real solution is handle the cases where an SQLException is caused by a broken connection by restarting the transaction.
Upvotes: 1