Friday, September 09, 2011

JDBC and Connection Timeout

If you want your jdbc driver connection not to wait more than a specified time even if the instance is down you may think that DriverManager.setLoginTimeout(seconds) is your friend. But if you test it with different drivers you will notice that for some it works and for some it does not.. So you are tight to the driver implementation which in many cases is not desirable.Given the fact that you can wait more than 30 seconds for a connection if the instance is down, it is imperative to look for alternatives.

The only general solution to this problem is to have a separate thread where you try to get the connection. You can set a timeout to complete the task of getting that connection. In java, FutureTask can be used to accomplish this:

Connection connection;
FutureTask task = null;
try {
    task = new FutureTask(new Callable() {
        @Override
        public Connection call() throws Exception {
            return DriverManager.getConnection(url, username, password);
        }
    });
    new Thread(task).start();
    connection = task.get(getConnectionTimeout(), TimeUnit.SECONDS);
} catch (Exception e) {
    throw new ConnectionException("Could not establish connection.", e);
}

No comments: