ExecutorCompletionService Finish Order

Drain finished tasks in completion order with ExecutorCompletionService take(), so slow submissions never delay already-finished results.

JavaData Fetching

Code

snippet
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ThumbnailPipeline {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        CompletionService<String> service = new ExecutorCompletionService<>(pool);

        String[] images = {"banner", "avatar", "logo", "og-image", "favicon"};
        for (String image : images) {
            service.submit(() -> {
                Thread.sleep(100 + image.length() * 40L); // 越长的名字渲染越慢
                return image + ".webp";
            });
        }

        // take() 阻塞等下一张完成:结果按完成顺序出来,与提交顺序无关
        try {
            for (int finished = 1; finished <= images.length; finished++) {
                Future<String> done = service.take();
                System.out.println(finished + ": " + done.get());
            }
        } catch (ExecutionException e) {
            System.err.println("render failed: " + e.getCause());
        } finally {
            pool.shutdown();
            pool.awaitTermination(5, TimeUnit.SECONDS);
        }
    }
}

What the code does

The moving parts are the class ThumbnailPipeline.

The loop for (String image : images) is the only repeated construct.

Iteration is driven by for (String image : images) and for (int finished = 1; finished <= images.length; finished++).

Statements that matter

ExecutorService pool = Executors.newFixedThreadPool(3);
Thread.sleep(100 + image.length() * 40L); // 越长的名字渲染越慢
return image + ".webp";

FAQ

How do you run ExecutorCompletionService Finish Order?
Run the file on its own; every call resolves against the standard surface it already imports.