public interface Executor {
// Execute a Runnable task
void execute(Runnable command);
}
public interface ExecutorService extends Executor {
// Submit a task with potential return value
Future submit(Callable task);
// Shutdown the executor
void shutdown();
}
public interface Callable {
// Task with a return value
V call() throws Exception;
}
public interface Future {
// Get the result of the task
V get() throws InterruptedException, ExecutionException;
// Check if task is complete
boolean isDone();
// Attempt to cancel the task
boolean cancel(boolean mayInterruptIfRunning);
}
// Example usage
ExecutorService executor = Executors.newFixedThreadPool(4);
Future future = executor.submit(() -> {
// Perform computation
return calculateResult();
});
// Wait for and retrieve result
Integer result = future.get();
public class AdvancedExecutionTechniques {
public void demonstrateAdvancedMethods() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(4);
// Execute multiple tasks and wait for all results
List> tasks = Arrays.asList(
() -> calculateTask(1),
() -> calculateTask(2),
() -> calculateTask(3)
);
// Wait for all tasks to complete
List> results = executor.invokeAll(tasks);
// Execute tasks, return first completed result
Integer firstResult = executor.invokeAny(tasks);
// Execute with timeout
try {
Integer timeoutResult = executor.invokeAny(
tasks, 2, TimeUnit.SECONDS
);
} catch (TimeoutException e) {
// Handle timeout scenario
}
executor.shutdown();
}
private int calculateTask(int input) {
// Simulate task computation
return input * input;
}
}