How can I set a timer in Java to attempt a database connection for 2 minutes before throwing an exception?

A more modern approach using CompletableFuture allows setting a timeout while attempting the database connection asynchronously.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.*;

public class DatabaseConnector {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            while (true) {
                try {
                    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
                    System.out.println("Connected successfully!");
                    return;
                } catch (SQLException e) {
                    System.out.println("Retrying in 5 seconds...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ignored) {}
                }
            }
        }, executor);

        try {
            future.get(2, TimeUnit.MINUTES); // Timeout after 2 minutes
        } catch (TimeoutException e) {
            future.cancel(true);
            throw new RuntimeException("Failed to connect within 2 minutes.", e);
        } catch (Exception e) {
            throw new RuntimeException("Unexpected error occurred.", e);
        } finally {
            executor.shutdown();
        }
    }
}

:white_check_mark: Why use this?

  • Non-blocking execution.
  • Automatically stops after 2 minutes without needing manual checks.

:rotating_light: When to avoid?

  • If your application doesn’t use CompletableFuture yet and you prefer simpler solutions.