0

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

3 Answers 3

3
try{
    //try to connect
}catch(com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException ex) {
    //what ever you want to do
}

Also See :

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for, I embedded it in a while loop. Thank you.
1

Use a connection pool like as for example C3P0. A bit decent connection pool can wait a certain timeout and retry a certain amount of times until a connection is available and then return it. Also ensure that you call Connection#close() in finally block of every try where you acquire the connection. Otherwise the connection is never released to pool (or to the database when you don't use a pool) and you will run out of them anyway.

1 Comment

Thanks for the suggestion, I didn't know C3P0. All my connections are closed, it's a cluster thing.
0

Something like should work better.

try 
{
    Connection cn = DriverManager.getConnection(url, username, password);
} 
catch ( com.mysql.jdbc.exceptions.MySQLNonTransientConnection e ) 
{
    // wait ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.