LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 3

Tasks on a single-thread executor Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links