Executor Rejection Policy Choices

See what a saturated ThreadPoolExecutor does with new tasks: AbortPolicy throws RejectedExecutionException, CallerRunsPolicy runs the task in the submitter.

JavaResilience

Code

snippet
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class RejectPolicyDemo {

    public static void main(String[] args) {
        // 单线程 + SynchronousQueue:worker 一忙,新任务立刻被拒,策略完全可控
        runWith("abort", new ThreadPoolExecutor(
                1, 1, 0L, TimeUnit.SECONDS,
                new SynchronousQueue<>(),
                new ThreadPoolExecutor.AbortPolicy()));
        runWith("caller-runs", new ThreadPoolExecutor(
                1, 1, 0L, TimeUnit.SECONDS,
                new SynchronousQueue<>(),
                new ThreadPoolExecutor.CallerRunsPolicy()));
    }

    static void runWith(String label, ThreadPoolExecutor pool) {
        AtomicInteger executed = new AtomicInteger();
        for (int i = 1; i <= 3; i++) {
            try {
                pool.execute(() -> {
                    sleep(200); // 占住 worker,制造后续任务被拒的窗口
                    executed.incrementAndGet();
                });
            } catch (RejectedExecutionException e) {
                System.out.println(label + ": task " + i + " rejected");
            }
        }
        pool.shutdown();
        try {
            pool.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        System.out.println(label + ": executed = " + executed.get());
    }

    static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

How the snippet works

Structurally, expect the class RejectPolicyDemo and the functions main, runWith and sleep and nothing else.

Repetition is confined to for (int i = 1; i <= 3; i++) — the rest of the file is straight-line.

Applying it

Treat main as the orchestrator calling runWith and sleep in a fixed order.

Statements that matter

Thread.currentThread().interrupt();
Thread.sleep(ms);
runWith("caller-runs", new ThreadPoolExecutor(
        1, 1, 0L, TimeUnit.SECONDS,
        new SynchronousQueue<>(),
        new ThreadPoolExecutor.CallerRunsPolicy()));

Interactive Tools for This Topic

FAQ

How do you run Executor Rejection Policy Choices?
Nothing to install first — run the file and the program does the rest.