1. Basic Executor Interface

Technical Explanation

  • Core Concept: Decouple task submission from execution
  • Key Methods:
    • execute(): Run a Runnable task
    • submit(): Submit a task with return value
    • shutdown(): Graceful executor termination
  • Design Pattern: Command pattern implementation

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();
}
                                        

2. Callable and Future Mechanisms

Technical Explanation

  • Callable: Task that returns a value
  • Future: Represents pending task result
  • Key Methods:
    • get(): Retrieve task result
    • isDone(): Check task completion
    • cancel(): Attempt to cancel task
  • Synchronization: Blocks until result available

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();
                                        

3. Advanced Execution Techniques

Technical Explanation

  • invokeAll(): Execute multiple tasks simultaneously
  • invokeAny(): Execute tasks, return first completed result
  • Timeout Handling: Prevent indefinite waiting
  • Error Management: Centralized exception handling

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;
    }
}