MySQL with Java: Open connection only if possible
- by emempe
I'm running a database-heavy Java application on a cluster, using Connector/J 5.1.14. Therefore, I have up to 150 concurrent tasks accessing the same MySQL database. I get the following error:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Too many connections
This happens because the server can't handle so many connections. I can't change anything on the database server. So my question is: Can I check if a connection is possible BEFORE I actually connect to the database?
Something like this (pseudo code):
check database for open connection slots
if (slot is free) {
Connection cn = DriverManager.getConnection(url, username, password);
}
else {
wait ...
}
Cheers