How to force timeout to drivermanager Getconnection () method call?
I have an application that will establish a database connection with MySQL and execute queries Sometimes, drivermanager The getconnection () method call takes 2 seconds, sometimes 30 seconds Is there any way to control the timeout after 2 seconds?
DriverManager. Setlogintimeout() does not seem to work
In fact, I can sleep the thread to the timeout value and close the connection after waking up Executequery() set timeout But in the connection establishment part, I can't really set the timeout
Thank you very much for any help
Solution
If there are no other options, you can always execute the call in a single thread. If it does not complete within 2 seconds, you will abort / ignore the thread
Editor: here is an example of my idea:
public class Dummy extends Thread { private volatile Connection conn = null; @Override public void run() { try { this.conn = DriverManager.getConnection("foobar") ; } catch (sqlException e) { e.printStackTrace(); } } static public Connection getConnection() { Dummy d = new Dummy() ; d.start() ; try { Thread.sleep(2000) ; } catch (InterruptedException e) {} return d.conn ; } }
Then, you can call static dummy. XML elsewhere in your code Getconnection () method One disadvantage is that this method always takes 2 seconds, but it's not too difficult to change it to return immediately when the thread completes