import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
public class FilePathImporter {
/**
* Imports file paths from a list of file paths with a timeout.
*
* @param filePaths A list of file paths to import.
* @param timeoutMs The timeout in milliseconds.
* @return A list of valid file paths.
* @throws IllegalArgumentException if filePaths is null or empty, or timeoutMs is negative.
*/
public static List<String> importFilePathsWithTimeout(List<String> filePaths, long timeoutMs) {
if (filePaths == null || filePaths.isEmpty()) {
throw new IllegalArgumentException("File paths list cannot be null or empty.");
}
if (timeoutMs < 0) {
throw new IllegalArgumentException("Timeout must be a non-negative value.");
}
List<String> validFilePaths = new ArrayList<>();
ExecutorService executor = Executors.newFixedThreadPool(filePaths.size()); //Use a thread pool for parallel processing.
for (String filePath : filePaths) {
Callable<String> task = () -> {
File file = new File(filePath);
if (file.exists() && file.isFile()) {
return filePath; // Return the path if it's a valid file.
} else {
return null; // Return null if it's not a valid file.
}
};
Future<String> future = executor.submit(task);
try {
String filePathResult = future.get(timeoutMs, java.util.concurrent.TimeUnit.MILLISECONDS); // Get the result with timeout
if (filePathResult != null) {
validFilePaths.add(filePathResult);
}
} catch (TimeoutException e) {
System.err.println("Timeout occurred while processing file: " + filePath);
// Handle timeout (e.g., log, retry, skip)
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Interrupted while processing file: " + filePath);
} catch (ExecutionException e) {
System.err.println("Exception while processing file: " + filePath + " - " + e.getMessage());
}
}
executor.shutdown(); // Shutdown the executor after all tasks are submitted.
return validFilePaths;
}
}
Add your comment