What is Callable and Future in Java concurrency

๐Ÿ’ก Concept: Callable and Future

Callable and Future are used to perform tasks in threads that return results and may throw exceptions. They provide a more flexible alternative to Runnable.

๐Ÿ“˜ Quick Intro

Callable is a functional interface that returns a result and can throw checked exceptions. Future is used to retrieve the result of a Callable task.

๐Ÿง  Analogy

Think of Callable like ordering food online โ€” you're promised a result. Future is the receipt that lets you check the status and get your food (result) when it's ready.

๐Ÿ”ง Technical Explanation

  • Callable<V> has a call() method that returns a value of type V.
  • ExecutorService.submit(Callable) returns a Future<V>.
  • Future.get() blocks until the result is available or an exception occurs.
  • Future also provides methods like cancel(), isDone(), and isCancelled().

๐ŸŽฏ Use Cases

  • โœ… Performing parallel computations and aggregating results.
  • โœ… Running background tasks that return values (e.g., file reading).
  • โœ… Timed tasks where cancellation is required.

๐Ÿ’ป Example: Callable and Future


import java.util.concurrent.*;

public class CallableExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        Callable task = () -> {
            Thread.sleep(1000);
            return "Task completed";
        };

        Future future = executor.submit(task);

        System.out.println("Waiting for result...");
        String result = future.get(); // blocks until result is ready
        System.out.println("Result: " + result);

        executor.shutdown();
    }
}

โ“ Interview Q&A

Q1: What does Callable interface do?
A: Represents a task that returns a result and may throw exceptions.

Q2: What does Future.get() do?
A: Waits for the result of a Callable task.

Q3: How is Callable different from Runnable?
A: Callable returns a result and can throw checked exceptions.

Q4: Can Future be cancelled?
A: Yes, using future.cancel().

Q5: What is isDone() in Future?
A: Checks if the task has completed.

Q6: Does Future support timeout?
A: Yes, get(timeout, unit) method exists.

Q7: Can Future be reused?
A: No, it's for one-time use per task.

Q8: Which package contains Callable and Future?
A: java.util.concurrent.

Q9: Can multiple threads use the same Callable instance?
A: Yes, if it's stateless or thread-safe.

Q10: How to execute multiple Callables?
A: Use invokeAll() with a list of Callables.

๐Ÿ“ MCQs

Q1. What does Callable return?

  • Nothing
  • Only boolean
  • A result or exception
  • Only exceptions

Q2. Which method executes a Callable?

  • start()
  • call()
  • submit()
  • execute()

Q3. What does Future.get() do?

  • Returns immediately
  • Throws exception
  • Blocks until the task is complete
  • Starts new thread

Q4. Which interface allows retrieving result from thread?

  • Runnable
  • Thread
  • Future
  • Executor

Q5. How do you cancel a task?

  • Thread.stop()
  • Executor.shutdown()
  • future.cancel()
  • task.abort()

Q6. Is Callable part of java.util.concurrent?

  • No
  • Yes
  • Only in Java 11
  • Only for lambdas

Q7. Can Callable throw checked exceptions?

  • No
  • Yes
  • Only RuntimeException
  • Only IOException

Q8. What does Future.isDone() check?

  • Thread is alive
  • Task is cancelled
  • Whether the task is completed
  • Task has errors

Q9. Which Executor method returns a Future?

  • execute()
  • invoke()
  • start()
  • submit()

Q10. What does invokeAll() do?

  • Cancels tasks
  • Executes Runnable
  • Executes a list of Callables
  • Creates threads

๐Ÿ’ก Bonus Insight

Use CompletableFuture for more advanced async programming with chaining and non-blocking operations in Java 8+.

๐Ÿ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

๐Ÿ” Navigation

Share:

Tags:


Feedback Modal Popup