"1Z0-809: Java SE 8 Programmer II"

"Result of Java SE 8 Programmer II Exam"

Question

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?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The given code creates an ExecutorService with a cached thread pool and uses it to execute multiple instances of the FileThread class in parallel to print the names of all the files in the "Java Projects" directory. The FileThread class implements the Runnable interface and takes a file name as a constructor argument, which is printed in the run() method.

Let's go through the code step by step:

  1. ExecutorService executor = Executors.newCachedThreadPool(); creates a new ExecutorService with a cached thread pool. A cached thread pool creates new threads as needed, but will reuse previously constructed threads when they are available.

  2. Stream<Path> listOfFiles = Files.walk(Paths.get("Java Projects")); creates a stream of all files and directories in the "Java Projects" directory and its subdirectories.

  3. listOfFiles.forEach(line ->{ executor.execute(new FileThread(line.getFileName().toString())); }); uses the forEach method of the Stream class to iterate over each Path object in the stream and execute a new FileThread instance for each file in parallel. The file name is obtained from the Path object using line.getFileName().toString().

  4. executor.shutdown(); shuts down the ExecutorService after all tasks have been submitted.

  5. executor.awaitTermination(5, TimeUnit.DAYS); waits for the ExecutorService to complete all tasks for up to 5 days.

Since the program is using a cached thread pool, multiple threads can be used to print the file names in parallel. Therefore, the program is expected to print file names concurrently.

Thus, the answer is B: The program prints files names concurrently.