Friday, 9 September 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);
}

1 comment:

  1. Great Article android based projects

    Java Training in Chennai

    Project Center in Chennai

    Java Training in Chennai

    projects for cse

    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete