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.
call() methodget(), isDone()Click the button to visualize how Callable submits a task and Future waits for the result.
// 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();
}
}
Result: 42
The Callable task runs in a separate thread. The get() method waits until execution is complete and then returns the computed value.
get() on UI threadsisDone() before calling get()