Question 3
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
List<String> log = new ArrayList<>(); // safe: only one worker thread touches it
try (ExecutorService single = Executors.newSingleThreadExecutor()) {
single.submit(() -> log.add("open"));
single.submit(() -> { try { Thread.sleep(50); } catch (InterruptedException e) { } log.add("write"); });
single.submit(() -> log.add("close"));
}
System.out.println(log);
}
}
- A [open, write, close] Correct
- B [open, close, write]
- C [write, open, close]
- D The order varies
Correct Answer: Option A
A single-thread executor runs tasks one at a time in submission order, even if one is slow.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!