Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Multithreading

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Multithreading

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 chain of stages on a pool thread. supplyAsync fetches 52000. thenApply adds 18% tax giving 61360. thenApply turns it into "$61360". thenAccept prints Laptop: $61360 and returns nothing. Main builds the chain, prints its own line first, then waits at join. supplyAsync52000 thenApply+18%: 61360 thenApply"$61360" thenAcceptprints, no value main: builds the chain, prints first, then waits at join()
Each stage gets the previous stage's value when it's ready.

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

FutureCompletableFuture
Get the valuefuture.get() waitstotal.join() waits
Next stepyou write it after getthenApply, thenAccept
Two resultstwo gets, by handthenCombine

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.

Keep going in Java · 71 of 79

Previous
Java ExecutorService and Thread Pools
Next post
Java Locks, Deadlock and tryLock
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Work that hands back a result
  • A chain that passes the value along
  • Two results, combined when both are ready
  • Future or CompletableFuture
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.