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

Learn More About Java โ˜•

What is Java and its key features ๐Ÿ‘‰ Explained
Explain the Java Virtual Machine (JVM) ๐Ÿ‘‰ Explained
Difference between JDK, JRE, and JVM ๐Ÿ‘‰ Explained
What are Javaโ€™s main data types ๐Ÿ‘‰ Explained
Explain the concept of Object-Oriented Programming in Java ๐Ÿ‘‰ Explained
What is the difference between a class and an object ๐Ÿ‘‰ Explained
Explain encapsulation with an example ๐Ÿ‘‰ Explained
What is inheritance in Java and its types ๐Ÿ‘‰ Explained
Define polymorphism in Java with examples ๐Ÿ‘‰ Explained
What is abstraction in Java ๐Ÿ‘‰ Explained
Difference between abstract class and interface in Java ๐Ÿ‘‰ Explained
Explain method overloading and method overriding in Java ๐Ÿ‘‰ Explained
What are constructors in Java ๐Ÿ‘‰ Explained
What is the use of the static keyword in Java ๐Ÿ‘‰ Explained
Explain the difference between final, finally, and finalize in Java ๐Ÿ‘‰ Explained
Share:

Tags:


Feedback Modal Popup