Java SE 8 Programmer II — Question 28
Given the code fragment:
public class FileThread implements Runnable {
String fName;
public FileThread(String fName) { this.fName = fName; }
public void run () System.out.println(fName);}
public static void main (String[] args) throws IOException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
Stream<Path> listOfFiles = Files.walk(Paths.get("Java Projects")); listOfFiles.forEach(line -> { executor.execute(new FileThread(line.getFileName().toString())); // line n1
});
executor.shutdown();
executor.awaitTermination(5, TimeUnit.DAYS); // line n2
}
}
The Java Projects directory exists and contains a list of files.
What is the result?
Answer options
- A. The program throws a runtime exception at line n2.
- B. The program prints files names concurrently.
- C. The program prints files names sequentially.
- D. A compilation error occurs at line n1.
Correct answer: B
Explanation
The correct answer is B because the program uses an ExecutorService to execute the FileThread instances concurrently, allowing file names to be printed simultaneously. Options A and D are incorrect as there are no runtime exceptions or compilation errors in the provided code. Option C is also incorrect since the execution of threads is concurrent, not sequential.