In Java, Callable and Future are interfaces that are part of the java.util.concurrent
package, allowing for asynchronous programming. Callable is similar to Runnable but can return a result and throw checked exceptions. Future represents the result of an asynchronous computation, allowing you to retrieve the result once it's available.
The Callable
interface is a functional interface that can be used to make tasks that return a value. It has a single method called call()
. Here is a simple example:
import java.util.concurrent.Callable;
public class MyCallable implements Callable {
@Override
public String call() throws Exception {
return "Task executed successfully!";
}
}
The Future
interface represents the result of an asynchronous computation. It provides methods for checking if the computation is complete, waiting for its completion, and retrieving the result. Here's an example of using Callable
with Future
:
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class FutureExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
Future future = executor.submit(new MyCallable());
// Do other tasks...
// Get the result of the computation
String result = future.get();
System.out.println(result);
executor.shutdown();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?