1. Web Server Request Processing

Industry Context

  • Used in high-traffic web applications
  • Manage concurrent client requests
  • Prevent resource exhaustion

Scenario Details

  • Limited thread pool for request handling
  • Concurrent client request processing
  • Efficient resource utilization

public class WebServerRequestProcessor {
    // Create a fixed thread pool for handling requests
    private final ExecutorService requestExecutor = 
        Executors.newFixedThreadPool(10);
    
    public void handleClientRequest(ClientRequest request) {
        requestExecutor.submit(() -> {
            try {
                // Process the client request
                processRequest(request);
            } catch (Exception e) {
                handleRequestError(request, e);
            }
        });
    }
    
    private void processRequest(ClientRequest request) {
        // Simulate request processing
        System.out.println("Processing request: " + request);
        try {
            // Simulate variable processing time
            Thread.sleep((long) (Math.random() * 1000));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    private void handleRequestError(ClientRequest request, Exception e) {
        System.err.println("Error processing request: " + request);
        e.printStackTrace();
    }
    
    // Client request model
    public static class ClientRequest {
        private String clientId;
        private String requestData;
        
        public ClientRequest(String clientId, String requestData) {
            this.clientId = clientId;
            this.requestData = requestData;
        }
        
        @Override
        public String toString() {
            return "ClientRequest{" +
                   "clientId='" + clientId + '\'' +
                   ", requestData='" + requestData + '\'' +
                   '}';
        }
    }
    
    // Demonstration method
    public static void main(String[] args) {
        WebServerRequestProcessor server = 
            new WebServerRequestProcessor();
        
        // Simulate multiple client requests
        for (int i = 1; i <= 20; i++) {
            ClientRequest request = new ClientRequest(
                "Client-" + i, 
                "Request-Data-" + i
            );
            server.handleClientRequest(request);
        }
    }
}
                                        

2. Image Processing Pipeline

Industry Context

  • Used in photo editing and batch processing
  • Parallel image transformation
  • Optimize computational resources

Scenario Details

  • Concurrent image processing
  • Utilize multiple CPU cores
  • Efficient batch image transformation

public class ImageProcessingPipeline {
    // Create a cached thread pool for image processing
    private final ExecutorService imageProcessorExecutor = 
        Executors.newCachedThreadPool();
    
    public void processImages(List images) {
        List> processedImageFutures = new ArrayList<>();
        
        // Submit image processing tasks
        for (BufferedImage image : images) {
            Future processedImage = 
                imageProcessorExecutor.submit(() -> {
                    return applyImageFilters(image);
                });
            processedImageFutures.add(processedImage);
        }
        
        // Collect processed images
        List processedImages = new ArrayList<>();
        for (Future future : processedImageFutures) {
            try {
                processedImages.add(future.get());
            } catch (Exception e) {
                System.err.println("Image processing error: " + e.getMessage());
            }
        }
    }
    
    private BufferedImage applyImageFilters(BufferedImage image) {
        // Simulate complex image processing
        BufferedImage processedImage = new BufferedImage(
            image.getWidth(), image.getHeight(), 
            BufferedImage.TYPE_INT_RGB
        );
        
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                int rgb = image.getRGB(x, y);
                int processedRgb = processPixel(rgb);
                processedImage.setRGB(x, y, processedRgb);
            }
        }
        
        return processedImage;
    }
    
    private int processPixel(int rgb) {
        // Simulate image processing (e.g., grayscale conversion)
        int r = (rgb >> 16) & 0xFF;
        int g = (rgb >> 8) & 0xFF;
        int b = rgb & 0xFF;
        
        int grayValue = (r + g + b) / 3;
        return (grayValue << 16) | (grayValue << 8) | grayValue;
    }
}
                                        

3. Periodic Monitoring System

Industry Context

  • Used in system monitoring and logging
  • Scheduled background tasks
  • Resource health tracking

Scenario Details

  • Periodic system health checks
  • Scheduled logging and reporting
  • Background maintenance tasks

public class SystemMonitoringScheduler {
    // Create a scheduled thread pool for monitoring tasks
    private final ScheduledExecutorService monitoringScheduler = 
        Executors.newScheduledThreadPool(3);
    
    public void startMonitoring() {
        // Periodic system health check every 5 minutes
        monitoringScheduler.scheduleAtFixedRate(
            this::checkSystemHealth, 
            0, 5, TimeUnit.MINUTES
        );
        
        // Delayed log rotation task
        monitoringScheduler.schedule(
            this::rotateSystemLogs, 
            1, TimeUnit.HOURS
        );
        
        // Periodic resource cleanup
        monitoringScheduler.scheduleWithFixedDelay(
            this::performResourceCleanup, 
            0, 30, TimeUnit.MINUTES
        );
    }
    
    private void checkSystemHealth() {
        System.out.println("Performing system health check");
        // Check CPU usage, memory, disk space, etc.
        double cpuUsage = getCurrentCpuUsage();
        long availableMemory = getAvailableMemory();
        
        // Log or trigger alerts based on health metrics
        if (cpuUsage > 80 || availableMemory < 1024) {
            triggerAlert(cpuUsage, availableMemory);
        }
    }
    
    private void rotateSystemLogs() {
        System.out.println("Rotating system logs");
        // Implement log rotation logic
        // Move current logs to archive, create new log files
    }
    
    private void performResourceCleanup() {
        System.out.println("Performing resource cleanup");
        // Remove temporary files
        // Clear caches
        // Release unused resources
    }
    
    // Simulated methods for demonstration
    private double getCurrentCpuUsage() {
        return Math.random() * 100;
    }
    
    private long getAvailableMemory() {
        return (long) (Math.random() * 4096);
    }
    
    private void triggerAlert(double cpuUsage, long memory) {
        System.out.println("ALERT: High resource usage");
        System.out.println("CPU Usage: " + cpuUsage + "%");
        System.out.println("Available Memory: " + memory + "MB");
    }
}