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

If you prefer a simple and blocking solution, a loop with Thread.sleep() can help.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnector {
    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        while (System.currentTimeMillis() - startTime < 120_000) { // Try for 2 minutes
            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...");
                Thread.sleep(5000); // Wait before retrying
            }
        }
        throw new RuntimeException("Failed to connect within 2 minutes.");
    }
}

:white_check_mark: Why use this?

  • Very easy to implement with minimal dependencies.
  • Straightforward retry mechanism.

:rotating_light: When to avoid?

If you need a non-blocking or concurrent approach.