Java
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().
Exercise 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().
Show example solution
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);
}
}
Test yourself
-
What does ExecutorService replace?
- A class definition
- A stream operation
- Writing tests
- Hand-creating a Thread
Show answer
Hand-creating a Thread — ExecutorService replaces direct new Thread usage.
-
Complete the submit call
ExecutorService pool = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> { /* toplam */ return 9; };
int total = pool.____(task).get();
Show answer
ExecutorService pool = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> { /* toplam */ return 9; };
int total = pool.submit(task).get();
-
Match the concurrent concepts
- ExecutorService
- Task pool
- Callable
- Result-bearing task
- Future
- Pending result
- submit
- Sends the task
Next lesson: Reflection and annotation