Java Callable, Future and CompletableFuture
A Callable counts 128 orders in the background while main sends an email, and future.get() waits for the answer. A CompletableFuture chain adds 18% tax to 52000 and prints $61360 on a pool thread, and thenCombine adds a 2400 price and 150 shipping into 2550.
What you will learn
- Return a value from a background task with Callable
- Use the Future from submit as a claim ticket, with isDone and get
- Chain background steps with supplyAsync, thenApply and thenAccept
- Combine two results with thenCombine and wait with join
Before you start
- Java ExecutorService and thread pools
- Java built-in functional interfaces
Sometimes a background task needs to hand a value back, like the number of orders from a slow database query. Threads run in the background, so how do you get that value? With a Callable and a Future. The sleeps in these programs decide the order of the lines; on a very slow machine they could print a little differently.
Work that hands back a result
package org.studyeasy.s06l07;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Ex01_CallableFuture {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
// a Callable RETURNS a value; a Runnable cannot
Callable<Integer> countOrders = () -> {
Thread.sleep(1000); // a slow database query
return 128;
};
Future<Integer> future = pool.submit(countOrders); // no wait
System.out.println("main: sending email");
System.out.println("main: done yet? " + future.isDone());
int orders = future.get(); // waits here until 128 is ready
System.out.println("main: orders today: " + orders);
pool.shutdown();
}
}
main: sending email
main: done yet? false
main: orders today: 128
A Runnable's run returns void, so nothing comes back. A Callable's call returns a value, here an Integer. Submitting it to the pool returns a Future straight away: a claim ticket for a result that isn't ready yet. Main keeps working, and isDone() says false. get() waits right there until the worker returns 128. Delete return 128; and it no longer compiles as a Callable.
A chain that passes the value along
static int fetchPrice() { // a slow price service
try { Thread.sleep(500); } catch (InterruptedException e) { }
return 52000;
}
ExecutorService pool = Executors.newFixedThreadPool(2);
CompletableFuture<Void> done = CompletableFuture
.supplyAsync(() -> fetchPrice(), pool)
.thenApply(p -> { // when the price is ready
log("adding 18% tax to " + p);
return p * 118 / 100;
})
.thenApply(t -> "$" + t) // put a $ in front
.thenAccept(label -> log("Laptop: " + label));
log("pipeline built, main did not wait");
done.join(); // now main waits
pool.shutdown();
main: pipeline built, main did not wait
pool-1-thread-1: adding 18% tax to 52000
pool-1-thread-1: Laptop: $61360
A CompletableFuture lets you line up the next steps instead of waiting. supplyAsync starts the work on a pool thread, and main moves on, which is why main's line comes first. Each thenApply waits for the value before it, changes it and passes it on: 52000 plus 18% is 61360, then it gets a $ sign. thenAccept uses the value and returns nothing, so nothing is passed on from it. join() makes main wait at the end.
Two results, combined when both are ready
static int lookup(String what, int ms, int value) { // a slow service
try { Thread.sleep(ms); } catch (InterruptedException e) { }
log(what + " = " + value);
return value;
}
CompletableFuture<Integer> price = CompletableFuture
.supplyAsync(() -> lookup("price", 600, 2400), pool);
CompletableFuture<Integer> shipping = CompletableFuture
.supplyAsync(() -> lookup("shipping", 300, 150), pool);
// runs once BOTH results are in
CompletableFuture<Integer> total =
price.thenCombine(shipping, (p, s) -> p + s);
log("both lookups started");
log("Anna pays " + total.join());
main: both lookups started
pool-1-thread-2: shipping = 150
pool-1-thread-1: price = 2400
main: Anna pays 2550
Both lookups start together, one on each worker. Shipping is ready first, after 300 ms, and waits in its slot. The price arrives after 600 ms, and only then does thenCombine run (p, s) -> p + s. join() returns the result like get(), but without checked exceptions, so swapping in total.get() forces you to handle them.
Future or CompletableFuture
| Future | CompletableFuture | |
|---|---|---|
| Get the value | future.get() waits | total.join() waits |
| Next step | you write it after get | thenApply, thenAccept |
| Two results | two gets, by hand | thenCombine |
A Callable returns a value, a Future is the ticket for it, and a CompletableFuture passes it from stage to stage. Next: what happens when threads wait on each other's locks, in locks, deadlock and tryLock.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Concurrency: Processes, Threads and the Main Thread in Java
Every Java program runs as a process and starts on one thread, main. One cook takes 15 seconds for soup and salad; a second thread, Jack, brings it to 10. Then two threads add to one counter a million times each and count less than 2,000,000.
Creating Threads in Java: Thread, Runnable and Lambdas
Three ways to give a thread its job: an InvoiceMailer that extends Thread, a ReportTask record that implements Runnable, and a lambda. worker.run() prints main, worker.start() prints backup-worker, and two cashiers, Jack and Liam, scan items in an order that changes every run.
Java Thread Lifecycle: sleep, join and interrupt
A courier thread walks from NEW through RUNNABLE and TIMED_WAITING to TERMINATED while main WAITs at join. An interrupt wakes a sleeping download on report-3: one version retries it, the other returns. And a daemon status thread dies when the last user thread ends.
Java Race Conditions and synchronized
Two cashiers each sell a million tickets on one counter and the total comes out short, a different number every run, because sold++ is read, add, write. A synchronized method or a synchronized block on one shared lock gives exactly 2,000,000; a new Object() lock protects nothing.
