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

How to Implement a Database Connection Timeout in Java?

Mary-Kate Olsen
Release: 2024-12-20 03:18:09
Original
495 people have browsed it

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();
Copy after login

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
Copy after login

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
Copy after login

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();
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template