Home >Java >javaTutorial >How to Implement a Database Connection Timeout in Java?

How to Implement a Database Connection Timeout in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 03:18:09498browse

How to Implement a Database Connection Timeout in Java?

How to Set a Timer in Java

This question seeks to understand how to set a timer in Java, specifically for establishing a database connection with a timeout limit.

Setting a Timer

To create a timer, use the java.util.Timer class:

Timer timer = new Timer();

For a one-time task, schedule it with:

timer.schedule(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000); // 2 minutes in milliseconds

For a repeating task, schedule it with:

timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000, 2*60*1000); // 2 minutes interval

Timeout for Database Connection

To implement the timeout functionality, use an ExecutorService:

ExecutorService service = Executors.newSingleThreadExecutor();

try {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            // Database task
        }
    };

    Future<?> f = service.submit(r);

    f.get(2, TimeUnit.MINUTES); // Attempt task for 2 minutes
} catch (TimeoutException e) {
    // Task timed out
} finally {
    service.shutdown();
}

If the database connection succeeds or fails within 2 minutes, the task will execute normally. Otherwise, a TimeoutException will be thrown. However, the task will continue running in the background, so keep that in mind.

The above is the detailed content of How to Implement a Database Connection Timeout in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn