← Back to Chapters

Callable & Future in Advance Java

⚡ Callable & Future in Advance Java

? Quick Overview

In Advance Java, Callable and Future are part of the java.util.concurrent package. They are used to execute tasks asynchronously and retrieve results from threads.

? Key Concepts

  • Callable<V> returns a result and can throw exceptions
  • Future<V> represents the result of an async computation
  • Used with ExecutorService
  • Better alternative to Runnable when result is needed

? Syntax / Theory

  • Callable has a call() method
  • Future provides methods like get(), isDone()
  • Thread pool executes Callable tasks

? Interactive Simulation

Click the button to visualize how Callable submits a task and Future waits for the result.

 
System Idle. Ready to submit.
Thread State
IDLE
Future.isDone()
false
Future.get()
--

? Code Example

? View Code Example
// Callable task that returns a value
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class MyTask implements Callable {
public Integer call() throws Exception {
// Simulating some computation
Thread.sleep(1000);
return 42;
}
}

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

// Submitting Callable to executor
Future result = service.submit(new MyTask());

// Getting the result from Future
System.out.println("Result: " + result.get());

service.shutdown();
}
}

? Live Output / Explanation

Output

Result: 42

The Callable task runs in a separate thread. The get() method waits until execution is complete and then returns the computed value.

✅ Tips & Best Practices

  • Use Callable when you need a return value
  • Always shut down ExecutorService
  • Avoid blocking get() on UI threads
  • Prefer thread pools over manual thread creation

? Try It Yourself

  • Create a Callable that returns factorial of a number
  • Run multiple Callable tasks using a fixed thread pool
  • Check isDone() before calling get()