Java DataSource waitUntilDatabaseIsAvailable(DataSource dataSource, int timeoutSeconds)

Here you can find the source of waitUntilDatabaseIsAvailable(DataSource dataSource, int timeoutSeconds)

Description

Waits until timeout is reached or the database is available.

License

Apache License

Parameter

Parameter Description
dataSource DataSource to the database
timeoutSeconds Timeout in seconds

Exception

Parameter Description
TimeoutException if the timeout is reached

Declaration

public static void waitUntilDatabaseIsAvailable(DataSource dataSource, int timeoutSeconds)
        throws TimeoutException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.TimeoutException;

public class Main {
    /**// w  w w.j  av a  2s  .c om
     * Waits until timeout is reached or the database is available.
     *
     * @param dataSource     {@link DataSource} to the database
     * @param timeoutSeconds Timeout in seconds
     * @throws TimeoutException if the timeout is reached
     */
    public static void waitUntilDatabaseIsAvailable(DataSource dataSource, int timeoutSeconds)
            throws TimeoutException {
        long start = System.currentTimeMillis();
        long timeout = timeoutSeconds * 1000;
        boolean started = false;

        while (!started) {
            Connection connection = null;
            Statement statement = null;
            try {
                connection = dataSource.getConnection();
                statement = connection.createStatement();
                started = true;
            } catch (SQLException e) {
                if (start + timeout < System.currentTimeMillis())
                    throw new TimeoutException("timeout reached!");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                }
            } finally {
                try {
                    if (statement != null)
                        statement.close();
                    if (connection != null)
                        connection.close();
                } catch (SQLException e1) {
                }
            }
        }
    }
}

Related

  1. setUpJndiDatasource()
  2. sqlExe(DataSource dataSource, String sql)
  3. tableRecommendationExistsHsqdb(DataSource dataSource)
  4. update(DataSource dataSource, String sql, Object params[])
  5. update_Db(DataSource ds, String query)