Connection timeout for DriverManager getConnection

后端 未结 6 1870
梦毁少年i
梦毁少年i 2020-11-29 01:23

I am trying to connect to DB using the standard JDBC way

connection = DriverManager.getConnection(url, username, password);

Is there a maxi

6条回答
  •  执笔经年
    2020-11-29 02:20

    As bestro suggested, it's possible to use a future with an associated timeout. For example:

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future future = executor.submit(new Callable() {
    
        @Override
        public Connection call() throws Exception {
            Connection con = DriverManager.getConnection(url, username, password);
            return con;
        }
    });
    
    Connection con = null;
    try {
        con = future.get(5, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException ex) {
        Logger.getLogger(Scratch.class.getName()).log(Level.SEVERE, null, ex);
    }
    executor.shutdownNow();
    
    if (con == null) {
        System.out.println("Could not establish connection");
    } else {
        System.out.println("Connection established!");
    }
    

提交回复
热议问题