Java Callable and Future Simple Example

 

🧵 Java Callable and Future – Simple Example

💡 Overview

In Java, the Callable and Future interfaces are part of the java.util.concurrent package and provide a more powerful alternative to the traditional Runnable interface.

Both Runnable and Callable are designed for classes whose instances can be executed by another thread — but with one key difference:

InterfaceReturns Result?Throws Checked Exception?
Runnable❌ No❌ No
Callable✅ Yes✅ Yes

So, if you need a thread to return a result or throw a checked exception, Callable is the right choice.


⚙️ Key Concepts

  1. Callable Interface

    • Similar to Runnable, but defines a method call() that can return a result and throw exceptions.

    • Signature:

      V call() throws Exception;
  2. ExecutorService

    • Manages a pool of worker threads.

    • Handles thread creation, task scheduling, and shutdown gracefully.

  3. Future Interface

    • Represents the result of an asynchronous computation.

    • Allows you to retrieve the result using future.get() once the task completes.


🧩 Example: Callable and Future in Action

1️⃣ File: CallableExample.java

package threading; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Demonstrates the use of ExecutorService, Callable, and Future interfaces. * * <ul> * <li>Thread1 implements Callable and overrides call() to return the thread name.</li> * <li>ExecutorService uses a fixed thread pool to execute multiple tasks.</li> * <li>Future stores and retrieves the result returned by Callable.</li> * </ul> * * Author: Vinod Kariyathungal Kumaran */ public class CallableExample { public static void main(String[] args) throws InterruptedException, ExecutionException { // Create a fixed thread pool of 10 threads ExecutorService ex = Executors.newFixedThreadPool(10); Thread1 t1 = new Thread1(); // Submit the Callable task multiple times and print results for (int i = 0; i <= 10; i++) { Future<String> future = ex.submit(t1); System.out.println(future.get()); } // Shutdown the executor ex.shutdown(); } } /** * Thread1 implements Callable and returns the current thread's name. */ class Thread1 implements Callable<String> { @Override public String call() throws Exception { return Thread.currentThread().getName(); } }

🧾 Output

pool-1-thread-1 pool-1-thread-2 pool-1-thread-3 pool-1-thread-4 pool-1-thread-5 pool-1-thread-6 pool-1-thread-7 pool-1-thread-8 pool-1-thread-9 pool-1-thread-10 pool-1-thread-1

🧠 Explanation

  1. ExecutorService creates a pool of 10 threads.
    This means at most 10 threads can run concurrently.

  2. Each time we call ex.submit(t1), the executor picks an available thread from the pool and runs the task.

  3. The Future<String> returned by submit() is used to get the result from Thread1.call().

  4. The output shows that threads are reused by the executor (thread-1 appears again at the end).

 

No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts