Timing out a task in Java


I recently had a need to make an http call and timeout if it took longer than 2 seconds. In JavaScript this is easy, but… how do you do the same in Java? ivermectin 12mg tablet online It turns out it’s pretty easy in Java too, provided you have Java >= 8. does ivermectin make the bugs crawl more

The essential ingredient is a CompletableFuture. Here’s how you do it:

// Use Java >= 11 'cos of the use of var in the main method
// Paste this in a file called Hello.java
// Compile: javac Hello.java
// Run: java Hello

import java.util.concurrent.*;

public class Hello {
    public static void main(String[] args) {
        System.out.println("Calling method");

        try {
            var message = CompletableFuture
                .supplyAsync(() -> longRunningMethod())
                .get(2000, TimeUnit.MILLISECONDS);

        } catch (Exception e) {
            System.err.println("Error: " + e.getClass().getSimpleName());

    private static String longRunningMethod() {
        try {
            return "Hello World";
        } catch (InterruptedException e) {
            throw new RuntimeException("Caught interrupted exception");

And that’s essentially it. If the operation takes longer than the timeout an exception is thrown and you can catch it and decide what to do with it later. ivexterm tabletas longRunningMethod() has a bit of extra logic to deal with Java’s rules about checked exceptions, but that’s not essential to the technique.

If you have a void method you can use CompletableFuture.runAsync() instead of supplyAsync().

I thought this was pretty nifty 🙂

About the Author

I’ve got some experience writing code. I run quite a lot. The last book I read was about Gavrilo Princip. There’s about to be a thunderstorm here. Here is Johannesburg, South Africa. There is another Johannesburg in the USA. I know how to make chocolate sauce.