1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.concurrent.Callable;
  5. import java.util.concurrent.ExecutionException;
  6. import java.util.concurrent.ExecutorService;
  7. import java.util.concurrent.Executors;
  8. import java.util.concurrent.TimeoutException;
  9. public class FilePathImporter {
  10. /**
  11. * Imports file paths from a list of file paths with a timeout.
  12. *
  13. * @param filePaths A list of file paths to import.
  14. * @param timeoutMs The timeout in milliseconds.
  15. * @return A list of valid file paths.
  16. * @throws IllegalArgumentException if filePaths is null or empty, or timeoutMs is negative.
  17. */
  18. public static List<String> importFilePathsWithTimeout(List<String> filePaths, long timeoutMs) {
  19. if (filePaths == null || filePaths.isEmpty()) {
  20. throw new IllegalArgumentException("File paths list cannot be null or empty.");
  21. }
  22. if (timeoutMs < 0) {
  23. throw new IllegalArgumentException("Timeout must be a non-negative value.");
  24. }
  25. List<String> validFilePaths = new ArrayList<>();
  26. ExecutorService executor = Executors.newFixedThreadPool(filePaths.size()); //Use a thread pool for parallel processing.
  27. for (String filePath : filePaths) {
  28. Callable<String> task = () -> {
  29. File file = new File(filePath);
  30. if (file.exists() && file.isFile()) {
  31. return filePath; // Return the path if it's a valid file.
  32. } else {
  33. return null; // Return null if it's not a valid file.
  34. }
  35. };
  36. Future<String> future = executor.submit(task);
  37. try {
  38. String filePathResult = future.get(timeoutMs, java.util.concurrent.TimeUnit.MILLISECONDS); // Get the result with timeout
  39. if (filePathResult != null) {
  40. validFilePaths.add(filePathResult);
  41. }
  42. } catch (TimeoutException e) {
  43. System.err.println("Timeout occurred while processing file: " + filePath);
  44. // Handle timeout (e.g., log, retry, skip)
  45. } catch (InterruptedException e) {
  46. Thread.currentThread().interrupt();
  47. System.err.println("Interrupted while processing file: " + filePath);
  48. } catch (ExecutionException e) {
  49. System.err.println("Exception while processing file: " + filePath + " - " + e.getMessage());
  50. }
  51. }
  52. executor.shutdown(); // Shutdown the executor after all tasks are submitted.
  53. return validFilePaths;
  54. }
  55. }

Add your comment