Java : Callable with Examples
Callable (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Callable<V> methods.
Summary
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 ()
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
- API Examples
- BlockingQueue
- CancellationException
- ConcurrentHashMap.KeySetView
- ConcurrentLinkedDeque
- ConcurrentLinkedQueue
- ConcurrentMap
- ConcurrentModificationException
- ConcurrentSkipListSet
- Condition
- CopyOnWriteArrayList
- CopyOnWriteArraySet
- CountDownLatch
- CyclicBarrier
- Exchanger
- Executor
- ExecutorService
- Executors
- Future
- Future.State
- FutureTask
- InterruptedException
- Lock
- Runnable
- Semaphore
- Thread
- ThreadGroup
- ThreadLocal
- TimeUnit