Java : Callable with Examples

Callable (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Callable<V> methods.


Summary

A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.

Class diagram

try (final var executor = Executors.newSingleThreadExecutor()) {
    final var task = new Callable<String>() {
        @Override
        public String call() {
            System.out.println("Call!");
            return "abcd";
        }
    };

    System.out.println("-- submit --");
    final var future = executor.submit(task);

    final var ret = future.get();
    System.out.println("get : " + ret);
}

// Result
// ↓
//-- submit --
//Call!
//get : abcd

Methods

V call ()

Computes a result, or throws an exception if unable to do so.

final var callable = new Callable<String>() {
    @Override
    public String call() {
        return "abcd";
    }
};

final var ret = callable.call();
System.out.println(ret); // abcd
final var path = Path.of("R:", "java-work", "aaa.txt");
System.out.println(Files.exists(path)); // false

final var callable = new Callable<String>() {
    @Override
    public String call() throws IOException {
        // The file is not found.
        return Files.readString(path);
    }
};

try {
    System.out.println("-- call --");
    callable.call();
} catch (IOException e) {
    System.out.println(e);
}

// Result
// ↓
//-- call --
//java.nio.file.NoSuchFileException: R:\java-work\aaa.txt
try (final var executor = Executors.newSingleThreadExecutor()) {
    System.out.println("-- submit --");
    final var future = executor.submit(() -> {
        System.out.println("Call!");
        return "abcd";
    });

    final var ret = future.get();
    System.out.println("get : " + ret);
}

// Result
// ↓
//-- submit --
//Call!
//get : abcd

Related posts

To top of page