×

java · level 3 · unit 6 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A reuses a few threads for many jobs.

Making a thread for every job is slow, and a thousand threads can sink a server. A thread pool keeps a small fixed team. Executors.newFixedThreadPool(3) gives you an with three threads, and submit(job) drops a job in its queue.

When the jobs are in, call : no new jobs, finish the old ones. Then awaitTermination(5, TimeUnit.SECONDS) waits for them, up to a time limit. Forget shutdown and the pool's threads keep the program alive after main ends.

Submitting after shutdown is refused with RejectedExecutionException, so shut down after the last submit, never inside the loop.

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main {
    public static void main(String[] args) throws InterruptedException {
        List<String> reviews = List.of("Great food", "Slow service but lovely staff", "Would come again", "Too loud");
        Map<String, Integer> words = new ConcurrentHashMap<>();
        ExecutorService pool = Executors.newFixedThreadPool(3);
        for (String review : reviews) {
            pool.submit(() -> words.put(review, review.split(" ").length));
        }
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println(new TreeMap<>(words));
    }
}

Three threads, four reviews: whichever thread is free first takes the next job from the queue.