CodeBlanks Logo Icon CodeBlanks

Concurrent layer

Write parallel pipelines with ExecutorService.

Total with ExecutorService

In this lesson you will compute the total severity concurrently with ExecutorService. Executors.newSingleThreadExecutor() creates a single-thread pool; submit takes a Callable.

ExecutorService pool = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> {
    int sum = 0;
    for (Event e : log) sum += e.severity;
    return sum;
};
int total = pool.submit(task).get();
pool.shutdown();

future.get() blocks until the task completes. In a single-thread pool the output order is deterministic, so the expected output is the same every time.

Callable and Future

Callable<V> is a task that returns a result; its call() method returns a value of type V. Future<V> holds a result that will appear later; .get() blocks until it is ready.

Callable<Integer> task = () -> {
    int sum = 0;
    for (Event e : log) sum += e.severity;
    return sum;
};

This task sums all severity levels in the list. You get the result with pool.submit(task).get().

Practice Compute the concurrent total

Use the previous lesson's log list. Create the pool with ExecutorService pool = Executors.newSingleThreadExecutor();. Write a Callable<Integer> task lambda that sums all severity levels in the list. Get the result with pool.submit(task).get() and print it. Finally call pool.shutdown().

Starter code

Main.java
import java.util.ArrayList;
import java.util.concurrent.*;

class Event {
    String type;
    int severity;
    Event(String type, int severity) {
        this.type = type;
        this.severity = severity;
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        ArrayList<Event> log = new ArrayList<>();
        log.add(new Event("info", 1));
        log.add(new Event("error", 5));
        log.add(new Event("warn", 3));
        // Compute total severity with ExecutorService
    }
}

Sample solution

Main.java
import java.util.ArrayList;
import java.util.concurrent.*;

class Event {
    String type;
    int severity;
    Event(String type, int severity) {
        this.type = type;
        this.severity = severity;
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        ArrayList<Event> log = new ArrayList<>();
        log.add(new Event("info", 1));
        log.add(new Event("error", 5));
        log.add(new Event("warn", 3));
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Callable<Integer> task = () -> {
            int sum = 0;
            for (Event e : log) sum += e.severity;
            return sum;
        };
        int total = pool.submit(task).get();
        pool.shutdown();
        System.out.println(total);
    }
}

Expected output

9

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does ExecutorService replace?

  • A class definition
  • A stream operation
  • Writing tests
  • Hand-creating a Thread Correct answer

Explanation: ExecutorService replaces direct new Thread usage.

2 Complete the submit call

Question
ExecutorService pool = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> { /* toplam */ return 9; };
int total = pool.____(task).get();
Answer
ExecutorService pool = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> { /* toplam */ return 9; };
int total = pool.submit(task).get();

Explanation: submit takes a Callable and returns a Future.

3 Match the concurrent concepts

Term Meaning
ExecutorService Task pool
Callable Result-bearing task
Future Pending result
submit Sends the task

All lessons in Advanced