Java : Future with Examples

Future (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Future methods.


Summary

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

Class diagram

final long current = System.nanoTime();
final DoubleSupplier elapsedTime = () -> (System.nanoTime() - current) / 1000000000.0;

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.printf("task : start (%f sec.)%n", elapsedTime.getAsDouble());
            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.printf("task : end (%f sec.)%n", elapsedTime.getAsDouble());
        }
    });

    TimeUnit.SECONDS.sleep(1);

    System.out.printf("future.get ... (%f sec.)%n", elapsedTime.getAsDouble());
    final var ret = future.get();

    System.out.printf("future.get OK! (%f sec.)%n", elapsedTime.getAsDouble());
    System.out.println("ret = " + ret);
}

// Result
// ↓
//task : start (0.002537 sec.)
//future.get ... (1.003706 sec.)
//task : end (2.004116 sec.)
//future.get OK! (2.004768 sec.)
//ret = abcd

Methods

boolean cancel (boolean mayInterruptIfRunning)

Attempts to cancel execution of this task.

final long current = System.nanoTime();
final DoubleSupplier elapsedTime = () -> (System.nanoTime() - current) / 1000000000.0;

class Task implements Callable<String> {
    private final String name;

    Task(String name) {
        this.name = name;
    }

    @Override
    public String call() {
        try {
            System.out.printf("%s : task start (%f sec.)%n", name, elapsedTime.getAsDouble());
            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.printf("%s : task end (%f sec.)%n", name, elapsedTime.getAsDouble());
        }
    }
}

try (final var executorService = Executors.newSingleThreadExecutor()) {
    System.out.println("submit A");
    final var futureA = executorService.submit(new Task("A"));

    TimeUnit.SECONDS.sleep(1);

    System.out.println("submit B");
    final var futureB = executorService.submit(new Task("B"));

    System.out.println("-- cancel tasks --");

    final var retA = futureA.cancel(false);
    System.out.printf("cancel A : ret = %b (%f sec.)%n", retA, elapsedTime.getAsDouble());

    // The task B has not yet started.
    final var retB = futureB.cancel(false);
    System.out.printf("cancel B : ret = %b (%f sec.)%n", retB, elapsedTime.getAsDouble());
}

System.out.println("-- end --");

// Result
// ↓
//submit A
//A : task start (0.002960 sec.)
//submit B
//-- cancel tasks --
//cancel A : ret = true (1.014476 sec.)
//cancel B : ret = true (1.014648 sec.)
//A : task end (2.016125 sec.)
//-- end --
final long current = System.nanoTime();
final DoubleSupplier elapsedTime = () -> (System.nanoTime() - current) / 1000000000.0;

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.printf("task start (%f sec.)%n", elapsedTime.getAsDouble());
            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.printf("task end (%f sec.)%n", elapsedTime.getAsDouble());
        }
    });

    TimeUnit.SECONDS.sleep(1);

    System.out.printf("cancel! (%f sec.)%n", elapsedTime.getAsDouble());
    final var ret = future.cancel(true);

    System.out.printf("cancel ret = %b%n", ret);
}

// Result
// ↓
//task start (0.003275 sec.)
//cancel! (1.004838 sec.)
//Interrupted!
//task end (1.005646 sec.)
//cancel ret = true
final long current = System.nanoTime();
final DoubleSupplier elapsedTime = () -> (System.nanoTime() - current) / 1000000000.0;

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.printf("task start (%f sec.)%n", elapsedTime.getAsDouble());
            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.printf("task end (%f sec.)%n", elapsedTime.getAsDouble());
        }
    });

    // Wait for the task to complete.
    System.out.println("get = " + future.get());

    final var ret = future.cancel(true);
    System.out.printf("cancel ret = %b (%f sec.)%n", ret, elapsedTime.getAsDouble());
}

// Result
// ↓
//task start (0.002477 sec.)
//task end (2.009747 sec.)
//get = abcd
//cancel ret = false (2.011178 sec.)

default Throwable exceptionNow ()

Returns the exception thrown by the task, without waiting.

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var futures = new ArrayList<Future<String>>();

    futures.add(executorService.submit(() -> "abc"));
    futures.add(executorService.submit(() -> "XYZ"));
    futures.add(executorService.submit(() -> {
        throw new IllegalStateException("Fail!");
    }));
    futures.add(executorService.submit(() -> "1234"));

    final var results = futures.stream()
            .filter(f -> f.state() == Future.State.SUCCESS)
            .map(Future::resultNow)
            .toList();

    System.out.println("results = " + results);

    final var exceptions = futures.stream()
            .filter(f -> f.state() == Future.State.FAILED)
            .map(Future::exceptionNow)
            .toList();

    System.out.println("exceptions = " + exceptions);
}

// Result
// ↓
//results = [abc, XYZ, 1234]
//exceptions = [java.lang.IllegalStateException: Fail!]

V get ()

Waits if necessary for the computation to complete, and then retrieves its result.

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- get start --");
    final var ret = future.get();

    System.out.println("-- get end --");
    System.out.println("ret = " + ret);
}

// Result
// ↓
//task start
//-- get start --
//task end
//-- get end --
//ret = abcd
try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);

            throw new IllegalStateException("Fail!");
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    TimeUnit.SECONDS.sleep(1);

    try {
        System.out.println("-- get start --");
        final var ret = future.get();

        System.out.println("-- get end --");
        System.out.println("ret = " + ret);
    } catch (ExecutionException e) {
        System.out.println("ExecutionException! : " + e.getMessage());
    }
}

// Result
// ↓
//task start
//-- get start --
//task end
//ExecutionException! : java.lang.IllegalStateException: Fail!
try (final var executorService = Executors.newScheduledThreadPool(2)) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(3);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    executorService.schedule(() -> {
        System.out.println("future.cancel");
        future.cancel(true);
    }, 2, TimeUnit.SECONDS);

    try {
        System.out.println("-- get start --");
        final var ret = future.get();

        System.out.println("-- get end --");
        System.out.println("ret = " + ret);
    } catch (CancellationException e) {
        System.out.println("CancellationException!");
    }
}

// Result
// ↓
//task start
//-- get start --
//future.cancel
//Interrupted!
//CancellationException!
//task end

V get (long timeout, TimeUnit unit)

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    TimeUnit.SECONDS.sleep(1);

    try {
        System.out.println("-- get start --");
        final var ret = future.get(3, TimeUnit.SECONDS);

        System.out.println("-- get end --");
        System.out.println("ret = " + ret);
    } catch (TimeoutException e) {
        System.out.println("TimeoutException!");
    }
}

// Result
// ↓
//task start
//-- get start --
//task end
//-- get end --
//ret = abcd
try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(3);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    TimeUnit.SECONDS.sleep(1);

    try {
        System.out.println("-- get start --");
        final var ret = future.get(1, TimeUnit.SECONDS);

        System.out.println("-- get end --");
        System.out.println("ret = " + ret);
    } catch (TimeoutException e) {
        System.out.println("TimeoutException!");
    }
}

// Result
// ↓
//task start
//-- get start --
//TimeoutException!
//task end

boolean isCancelled ()

Returns true if this task was cancelled before it completed normally.

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("-- task start --");
            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("-- task end --");
        }
    });

    TimeUnit.SECONDS.sleep(1);

    System.out.println("isCancelled = " + future.isCancelled());
    System.out.println("isDone = " + future.isDone());
    System.out.println("state = " + future.state());

    // Wait for the task to complete.
    System.out.println("get = " + future.get());

    System.out.println("isCancelled = " + future.isCancelled());
    System.out.println("isDone = " + future.isDone());
    System.out.println("state = " + future.state());

    System.out.println("----");
    System.out.println("cancel = " + future.cancel(false));
    System.out.println("isCancelled = " + future.isCancelled());
}

// Result
// ↓
//-- task start --
//isCancelled = false
//isDone = false
//state = RUNNING
//-- task end --
//isCancelled = false
//isDone = true
//state = SUCCESS
//----
//cancel = false
//isCancelled = false
try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("-- task start --");
            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("-- task end --");
        }
    });

    TimeUnit.SECONDS.sleep(1);

    System.out.println("isCancelled = " + future.isCancelled());
    System.out.println("isDone = " + future.isDone());
    System.out.println("state = " + future.state());

    System.out.println("----");
    System.out.println("cancel = " + future.cancel(false));

    System.out.println("isCancelled = " + future.isCancelled());
    System.out.println("isDone = " + future.isDone());
    System.out.println("state = " + future.state());
}

// Result
// ↓
//-- task start --
//isCancelled = false
//isDone = false
//state = RUNNING
//----
//cancel = true
//isCancelled = true
//isDone = true
//state = CANCELLED
//-- task end --
try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("-- task start --");
            TimeUnit.SECONDS.sleep(2);

            throw new IllegalStateException("Fail!");
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("-- task end --");
        }
    });

    TimeUnit.SECONDS.sleep(1);

    System.out.println("isCancelled = " + future.isCancelled());
    System.out.println("isDone = " + future.isDone());
    System.out.println("state = " + future.state());

    try {
        System.out.println("get = " + future.get());
    } catch (ExecutionException e) {
        System.out.println("ExecutionException! : " + e.getMessage());
    }

    System.out.println("isCancelled = " + future.isCancelled());
    System.out.println("isDone = " + future.isDone());
    System.out.println("state = " + future.state());
}

// Result
// ↓
//-- task start --
//isCancelled = false
//isDone = false
//state = RUNNING
//-- task end --
//ExecutionException! : java.lang.IllegalStateException: Fail!
//isCancelled = false
//isDone = true
//state = FAILED

boolean isDone ()

Returns true if this task completed.

Please see isCancelled().

default V resultNow ()

Returns the computed result, without waiting.

Please see exceptionNow().

default Future.State state ()

Returns the computation state.

Please see isCancelled().


Related posts

To top of page