Programming Search⌘K

Conceptcore

Executors

Also called executor, Executor, ExecutorService, TaskScheduler, task scheduler, async executor, block_on, launch policy.

An executor is an object that runs tasks. Code submits a task to it, and the executor decides when, where and on which thread the task runs.

Applies to
core-languages

Idea

An executor is an object that runs tasks. Code that has work to do gives a task to the executor, and the executor decides how the task runs: now or later, on the current thread or on another thread, alone or at the same time as other tasks. The Java documentation describes its Executor interface as "a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc."1

This split has two benefits. The code that submits tasks stays the same when the policy changes, so a program can move from one thread per task to a pool of threads by changing one line. And the policy is in one place, where it is easy to limit, measure and shut down.12 The example files show this. One function submits the same tasks to different executors, and each executor runs them in a different way.

How it works

The interface

The smallest executor interface has one operation: run this task. In Java, Executor has one method, execute(Runnable), which "Executes the given command at some time in the future".1 Most executor interfaces add two things:

  • A result. submit returns a future, an object that holds the result of the task when it is ready. Java ExecutorService.submit returns a Future that "can be used to cancel execution and/or wait for completion".2 Python Executor.submit returns a Future too.3 If the task raises an exception, the future keeps it, and result raises "the same exception" when the caller asks for the value.3
  • A lifecycle. An executor that owns threads must stop them. An ExecutorService "can be shut down, which will cause it to reject new tasks", and "An unused ExecutorService should be shut down to allow reclamation of its resources".2

Policies

The executor decides how each task runs. The Java documentation gives three examples:1

  • Direct. The executor runs the task "immediately in the caller's thread".1 This executor adds no concurrency.
  • A thread for each task. The executor "spawns a new thread for each task".1 Executors.newThreadPerTaskExecutor gives this policy, and newVirtualThreadPerTaskExecutor gives the same policy with virtual threads.4
  • Serial. A composite executor passes tasks to another executor one at a time, so they never overlap.1

The most common policy is a pool: a fixed set of worker threads takes tasks from a queue. Executors.newFixedThreadPool "reuses a fixed number of threads operating off a shared unbounded queue".4 A pool limits the number of threads, so it limits the parallel work and the memory for stacks. See Run tasks on a thread pool.

Queues and scheduling

Inside most executors, there is a queue of tasks that wait and one or more workers that take tasks from it. Tokio describes a scheduler in the same terms: a "run queue and a processor that drains the queue".5 The design choices are in the queue:

  • One queue or many. With one shared queue, all workers take from the same place, and the queue must support many producers and many consumers at the same time.5 With a queue for each worker, workers contend less, but a worker with no work must take tasks from the queue of another worker. This is Work stealing. The .NET default scheduler uses a global FIFO queue and a local queue for each thread of the pool, and "provides work-stealing for load-balancing".6
  • Bounded or unbounded. An unbounded queue accepts every task, but it can grow without limit "when commands continue to arrive on average faster than they can be processed".7 A bounded queue must say what happens to a task when it is full. Java calls this a rejection policy. The default throws RejectedExecutionException, and CallerRunsPolicy runs the task "directly in the calling thread".7

Executors for async code

Async code needs an executor too, because a coroutine or a future does not run by itself. In Rust, futures are "lazy: they won’t do anything unless actively driven to completion".8 An async executor takes futures and runs them "by calling poll whenever the Future can make progress".8 When a future cannot continue, it saves a waker. When the event that it waits for happens, the waker puts the future back in the queue, and the executor polls it again.8 The Rust example builds a minimal executor of this kind.

Rust has no async executor in its standard library: executors "are not yet provided in the standard library", and libraries such as Tokio supply them.9 An async runtime usually combines one or more executors with a reactor, which gives notice of events such as I/O and timers.9

In languages

LanguageVerdictNote
PythonStandard library
C++Absent
JavaStandard library
CAbsentThe C standard library has threads but no executor type. No separate example file. Alternative: A fixed set of threads that take jobs from a shared queue, as in the C solution of run-tasks-on-a-thread-pool.
C#Standard library
JavaScriptAbsent
TypeScriptAbsentTypeScript runs on a JavaScript engine, which has an event loop but no executor interface. No example file exists. Alternative: The event loop queues, as in the JavaScript example.
GoAbsent
RustLibrary
KotlinStandard libraryOn the JVM, Kotlin uses the Java executors, as in the Java example; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyThe database runs the query; a query does not submit tasks.
BashAbsentBash has no executor. No example file exists. Alternative: Background jobs with & and wait.
PowerShellAbsentPowerShell has no executor type; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: Background jobs with Start-Job.
HTMLDoes not applyMarkup has no tasks.
CSSDoes not applyStyle rules have no tasks.
Regular expressionsDoes not applyA pattern has no tasks.

All the tier 1 languages that have threads can use an executor. The difference is whether the standard library defines an executor interface, or whether the runtime has one fixed executor and no interface.

Language Verdict Mechanism
Python stdlib concurrent.futures.Executor, with ThreadPoolExecutor and ProcessPoolExecutor
JavaScript absent the event loop and its task and microtask queues
TypeScript absent as JavaScript
Java stdlib Executor, ExecutorService and the Executors factory methods
Kotlin stdlib the Java executors on the JVM
C# stdlib TaskScheduler, with the thread pool as the default
Go absent the go statement and the runtime scheduler
Rust library the Future trait in std; executors in crates such as Tokio
C absent threads from pthread_create or thrd_create
C++ absent std::async with a launch policy
Bash absent background jobs with &
PowerShell absent background jobs with Start-Job
SQL n/a the database runs the query
Regex n/a a pattern has no tasks
HTML/CSS n/a markup and style rules have no tasks
  • Java. Executor is the base interface. ExecutorService adds futures, bulk operations such as invokeAll, and shutdown.2 It extends AutoCloseable, so a try-with-resources block shuts the executor down and waits for its tasks.2
  • Python. concurrent.futures defines Executor as an abstract class that "should not be used directly, but through its concrete subclasses".3 Its thread and process executors share one interface, so a program can move CPU-bound work to processes by changing the class.3 In asyncio, loop.run_in_executor runs a blocking function in a concurrent.futures.Executor and gives the event loop a future for the result.10
  • C#. TaskScheduler "handles the low-level work of queuing tasks onto threads".6 Most code uses the default scheduler through Task.Run and await. A custom scheduler can limit concurrency or run tasks on one thread. ConcurrentExclusiveSchedulerPair gives two schedulers where "exclusive tasks never" run at the same time as other tasks.11
  • JavaScript. There is one thread and one event loop. A program chooses the queue, not the executor. A callback from queueMicrotask runs "only if the JavaScript execution stack is empty", before the event loop takes the next task, such as a setTimeout callback.12
  • Go. The runtime multiplexes goroutines "onto a set of threads", so a go statement is already a submission to an executor with a scheduler.13 To limit the work in progress, Go programs start a fixed number of goroutines that receive jobs from a channel.14
  • C++. std::async takes a launch policy. With std::launch::async, the function runs "as if in a new thread of execution". With std::launch::deferred, the first wait on the future runs the function "in the thread that called the waiting function".15
PythonGitHub
import threading
from concurrent.futures import Executor, Future, ThreadPoolExecutor


class InlineExecutor(Executor):
    """An executor that runs each task at once, in the caller's thread."""

    def submit(self, fn, /, *args, **kwargs):
        future = Future()
        try:
            future.set_result(fn(*args, **kwargs))
        except BaseException as error:
            future.set_exception(error)
        return future


def threads_used(executor, count):
    # This code knows only the Executor interface: submit a task, get a Future.
    futures = [executor.submit(threading.get_ident) for _ in range(count)]
    return {future.result() for future in futures}


caller = threading.get_ident()

with InlineExecutor() as executor:
    print("inline: ran on the caller's thread only:", threads_used(executor, 4) == {caller})

with ThreadPoolExecutor(max_workers=2) as executor:
    used = threads_used(executor, 4)
    print("pool of 2: at most 2 threads:", len(used) <= 2)
    print("pool of 2: used the caller's thread:", caller in used)
Output
inline: ran on the caller's thread only: True
pool of 2: at most 2 threads: True
pool of 2: used the caller's thread: False
  • Verdict: stdlib. concurrent.futures.Executor is an abstract class with submit, map and shutdown. ThreadPoolExecutor and ProcessPoolExecutor are its two implementations in the standard library.
  • threads_used submits tasks and reads their results through Future objects. It does not know which executor runs them.
  • InlineExecutor shows that an executor does not have to use other threads. Its submit runs the task at once and returns a future that is already done.
  • asyncio has its own model: an event loop runs coroutines, and loop.run_in_executor hands blocking calls to an executor.
#include <future>
#include <iostream>
#include <thread>

int main() {
    const auto caller = std::this_thread::get_id();
    auto task = [] { return std::this_thread::get_id(); };

    // The launch policy chooses how the same task runs.
    auto deferred = std::async(std::launch::deferred, task);
    auto async = std::async(std::launch::async, task);

    std::cout << std::boolalpha;
    std::cout << "deferred: ran on the caller's thread: " << (deferred.get() == caller) << '\n';
    std::cout << "async: ran on the caller's thread: " << (async.get() == caller) << '\n';
}
Output
deferred: ran on the caller's thread: true
async: ran on the caller's thread: false
  • Verdict: absent. The C++ standard library has no executor type. std::async with a launch policy is the nearest tool.
  • With std::launch::deferred, the task runs in the thread that calls get, when it calls get. With std::launch::async, it runs as if on a new thread.
  • std::async with no policy lets the library choose between the two.
JavaGitHub
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    // This code knows only the Executor interface. It returns the IDs of the threads that ran the tasks.
    static Set<Long> threadsUsed(Executor executor, int count) throws InterruptedException {
        Set<Long> threads = ConcurrentHashMap.newKeySet();
        CountDownLatch done = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            executor.execute(() -> {
                threads.add(Thread.currentThread().threadId());
                done.countDown();
            });
        }
        done.await();
        return threads;
    }

    public static void main(String[] args) throws InterruptedException {
        long caller = Thread.currentThread().threadId();

        Executor direct = Runnable::run;
        System.out.println("direct: ran on the caller's thread only: "
            + threadsUsed(direct, 4).equals(Set.of(caller)));

        try (ExecutorService perTask = Executors.newThreadPerTaskExecutor(Thread.ofPlatform().factory())) {
            System.out.println("thread per task: threads used: " + threadsUsed(perTask, 4).size());
        }

        try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
            System.out.println("pool of 2: at most 2 threads: " + (threadsUsed(pool, 4).size() <= 2));
        }
    }
}
Output
direct: ran on the caller's thread only: true
thread per task: threads used: 4
pool of 2: at most 2 threads: true
  • Verdict: stdlib. java.util.concurrent.Executor has one method, execute(Runnable). ExecutorService adds submit, futures and shutdown, and Executors has factory methods for common executors.
  • threadsUsed does not know how the tasks run. The same method runs them in the caller's thread, on a new thread each, and on a pool of two threads.
  • Runnable::run is the direct executor of the Executor documentation: it runs each task in the caller's thread.
  • A CountDownLatch waits for the tasks, because the Executor interface gives no way to wait.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

// A scheduler that runs each task at once, on the thread that queues it.
sealed class InlineScheduler : TaskScheduler
{
    protected override void QueueTask(Task task) => TryExecuteTask(task);

    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) =>
        TryExecuteTask(task);

    protected override IEnumerable<Task> GetScheduledTasks() => [];
}

static class Program
{
    static int running;
    static int maxRunning;

    // This code knows only the TaskScheduler. It returns the IDs of the threads that ran the tasks.
    static HashSet<int> ThreadsUsed(TaskScheduler scheduler, int count)
    {
        running = 0;
        maxRunning = 0;
        var tasks = Enumerable.Range(0, count).Select(_ => Task.Factory.StartNew(() =>
        {
            int now = Interlocked.Increment(ref running);
            int seen;
            while (now > (seen = Volatile.Read(ref maxRunning)) &&
                   Interlocked.CompareExchange(ref maxRunning, now, seen) != seen) { }
            Thread.Sleep(20);
            Interlocked.Decrement(ref running);
            return Environment.CurrentManagedThreadId;
        }, CancellationToken.None, TaskCreationOptions.None, scheduler)).ToArray();
        Task.WaitAll(tasks);
        return tasks.Select(t => t.Result).ToHashSet();
    }

    static void Main()
    {
        int caller = Environment.CurrentManagedThreadId;

        var inline = ThreadsUsed(new InlineScheduler(), 4);
        Console.WriteLine($"inline: ran on the caller's thread only: {inline.SetEquals([caller])}");

        var pool = ThreadsUsed(TaskScheduler.Default, 4);
        Console.WriteLine($"default: used the caller's thread: {pool.Contains(caller)}");

        var pair = new ConcurrentExclusiveSchedulerPair();
        ThreadsUsed(pair.ExclusiveScheduler, 4);
        Console.WriteLine($"exclusive: most tasks at the same time: {maxRunning}");
    }
}
Output
inline: ran on the caller's thread only: True
default: used the caller's thread: False
exclusive: most tasks at the same time: 1
  • Verdict: stdlib. TaskScheduler is the abstract class that puts tasks on threads. TaskScheduler.Default uses the .NET thread pool.
  • ThreadsUsed starts the same tasks on each scheduler. It does not know how the scheduler runs them.
  • InlineScheduler runs each task in its QueueTask call, on the thread that started it.
  • ConcurrentExclusiveSchedulerPair gives two schedulers. Tasks on its ExclusiveScheduler never run at the same time, so the most that run together is 1.
  • Most code uses Task.Run and async/await, which use the default scheduler. A custom scheduler is a rare tool.
JavaScriptGitHub
// Three ways to run a task. The code that submits the tasks is the same for each.
const executors = {
  direct: (task) => task(),
  microtask: (task) => queueMicrotask(task),
  timer: (task) => setTimeout(task, 0),
};

const log = [];
for (const [name, execute] of Object.entries(executors)) {
  execute(() => log.push(name));
}
log.push("all tasks submitted");

// Print the log when the event loop has run the queued tasks.
setTimeout(() => console.log(log.join("\n")), 20);
Output
direct
all tasks submitted
microtask
timer
  • Verdict: absent. JavaScript has no executor interface, but the event loop is an executor with fixed rules. A program chooses when a task runs by the queue that it puts the task in.
  • direct runs the task inside the call. queueMicrotask runs it when the current script has finished and the stack is empty. setTimeout puts it in the timer queue, which the event loop handles after the microtasks.
  • All three run on the main thread. For work on other threads, Node.js has worker_threads.
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"
)

// An Executor runs a task. This program uses three implementations.
type Executor func(task func())

func direct(task func()) { task() }

func goroutinePerTask(task func()) { go task() }

// pool returns an executor with a fixed number of workers, and a function that stops them.
func pool(workers int) (Executor, func()) {
	tasks := make(chan func())
	var wg sync.WaitGroup
	for range workers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for task := range tasks {
				task()
			}
		}()
	}
	execute := func(task func()) { tasks <- task }
	stop := func() { close(tasks); wg.Wait() }
	return execute, stop
}

// mostAtOnce runs count tasks with the executor and returns the most that ran at the same time.
func mostAtOnce(execute Executor, count int) int32 {
	var running, most atomic.Int32
	var done sync.WaitGroup
	done.Add(count)
	for range count {
		execute(func() {
			defer done.Done()
			now := running.Add(1)
			for {
				seen := most.Load()
				if now <= seen || most.CompareAndSwap(seen, now) {
					break
				}
			}
			time.Sleep(20 * time.Millisecond)
			running.Add(-1)
		})
	}
	done.Wait()
	return most.Load()
}

func main() {
	fmt.Println("direct: most at once:", mostAtOnce(direct, 4))
	fmt.Println("goroutine per task: most at once:", mostAtOnce(goroutinePerTask, 4))
	execute, stop := pool(2)
	fmt.Println("pool of 2: most at once:", mostAtOnce(execute, 4))
	stop()
}
Output
direct: most at once: 1
goroutine per task: most at once: 4
pool of 2: most at once: 2
  • Verdict: absent. Go has no executor type, because the go statement and the runtime scheduler do this work. A program that needs another policy, such as a limit on the number of workers, writes a small executor with a channel.
  • Executor here is a function type. mostAtOnce uses only that type, so the same code runs with each policy.
  • The pool limits the work to two tasks at the same time. A goroutine for each task has no limit.
RustGitHub
use std::future::Future;
use std::pin::{pin, Pin};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
use std::time::Duration;

// A future that a helper thread completes after a delay.
struct Delay {
    state: Arc<Mutex<(bool, Option<Waker>)>>,
    started: bool,
}

impl Delay {
    fn new() -> Self {
        Delay { state: Arc::new(Mutex::new((false, None))), started: false }
    }
}

impl Future for Delay {
    type Output = &'static str;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut state = self.state.lock().unwrap();
        if state.0 {
            return Poll::Ready("done");
        }
        state.1 = Some(cx.waker().clone());
        drop(state);
        if !self.started {
            self.started = true;
            let shared = Arc::clone(&self.state);
            thread::spawn(move || {
                thread::sleep(Duration::from_millis(20));
                let mut state = shared.lock().unwrap();
                state.0 = true;
                if let Some(waker) = state.1.take() {
                    waker.wake();
                }
            });
        }
        Poll::Pending
    }
}

// The waker of this executor sets a flag and unparks the thread that runs block_on.
struct ThreadWaker {
    thread: Thread,
    woken: AtomicBool,
}

impl Wake for ThreadWaker {
    fn wake(self: Arc<Self>) {
        self.woken.store(true, Ordering::Release);
        self.thread.unpark();
    }
}

// A minimal executor: poll the future, and sleep until its waker is called.
fn block_on<F: Future>(future: F) -> (F::Output, u32) {
    let signal = Arc::new(ThreadWaker { thread: thread::current(), woken: AtomicBool::new(false) });
    let waker = Waker::from(Arc::clone(&signal));
    let mut cx = Context::from_waker(&waker);
    let mut future = pin!(future);
    let mut polls = 0;
    loop {
        polls += 1;
        if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
            return (value, polls);
        }
        while !signal.woken.swap(false, Ordering::Acquire) {
            thread::park();
        }
    }
}

fn main() {
    let future = Delay::new();
    println!("created the future; nothing has run yet");
    let (value, polls) = block_on(future);
    println!("result: {value}");
    println!("polls: {polls}");
}
Output
created the future; nothing has run yet
result: done
polls: 2
  • Verdict: library. The standard library has the Future trait and the Waker type, but no executor. Programs choose one from a crate, such as Tokio.
  • A Rust future does nothing until an executor polls it. block_on polls the future once, and the future returns Pending.
  • The future gives the waker to its helper thread. When the thread calls wake, the executor polls again and gets the result. So there are two polls.
  • The woken flag makes the loop ignore a park that returns without a wake.
  • Thread pool. A thread pool is the most common executor. Run tasks on a thread pool shows one in each language.
  • Work stealing. A scheduler design with a queue for each worker. An idle worker takes tasks from the queues of busy workers.65
  • Scheduled executors. Some executors run tasks after a delay or at a fixed rate. Java has newScheduledThreadPool in Executors.4
  • Futures and promises. The object that submit returns. An executor runs the task; the future gives the result to the caller.23
  • Virtual threads. Java can run each task on its own virtual thread with newVirtualThreadPerTaskExecutor.4
  • Async/await. Async functions need an executor to run. In JavaScript the event loop is the executor; in Rust the program chooses one.812

Pitfalls

  • Tasks that wait for other tasks. If a task waits for the result of another task on the same executor, and all workers are busy with tasks that wait, no task can continue. Python warns: "Deadlocks can occur when the callable associated with a Future waits on the results of another Future".3 The Run tasks on a thread pool page shows this with a single worker.
  • Lost exceptions. An exception in a task goes into its future. If no code asks the future for its result, no one sees the exception.3
  • No shutdown. An executor that is not shut down keeps its threads and other resources.2 Use the lifecycle tools of the language, such as with in Python or try-with-resources in Java.
  • Unbounded queues. A fixed pool with an unbounded queue accepts tasks faster than it runs them, and the queue grows.7 Use a bounded queue with a rejection policy when tasks can arrive faster than workers finish them.
  • Thread affinity. An executor can run a task on any of its threads. Code that must run on one thread, such as UI code, needs a scheduler for that thread. In .NET, TaskScheduler.FromCurrentSynchronizationContext gives one, because UI access is often "restricted to code that is running on the same thread on which the UI object was created".6
  • Blocking in async code. A blocking call in a task of an async executor also stops the other tasks of that worker. In Python, run_in_executor runs such calls in a thread or process executor instead.10

Cost

  • Submission. A submission puts a task in a queue, and a worker takes it later. A shared queue has contention when many threads use it at the same time; a queue for each worker reduces this.56
  • Threads. A pool keeps its threads after a task ends, so later tasks do not pay to create a thread.4 A thread for each task pays that cost each time, unless the threads are virtual threads.
  • Direct execution. A direct executor costs only a function call, and it adds no parallelism.1

History

J2SE 5.0 came out in September 2004 with the concurrency utilities in java.util.concurrent.16 The Executor interface is part of that package, and its documentation lists 1.5 as its first version.1 Rust took a different path: its standard library defines futures but leaves executors to libraries such as Tokio.9 In 2019 the Tokio project rewrote its scheduler and described the choices: one shared run queue, or a run queue for each processor with work stealing, which Go, Erlang and Java also use.5

References

  1. Java SE 21 API, java.util.concurrent.Executor, interface description; execute
  2. Java SE 21 API, java.util.concurrent.ExecutorService, interface description; close
  3. Python documentation, concurrent.futures, Executor Objects; Future Objects; ThreadPoolExecutor
  4. Java SE 21 API, java.util.concurrent.Executors, Method Summary
  5. Tokio blog, Making the Tokio scheduler 10x faster (2019), One queue, many processors; Many processors, each with their own run queue
  6. Microsoft Learn, TaskScheduler class, Remarks; The default task scheduler and the thread pool; Task inlining
  7. Java SE 21 API, java.util.concurrent.ThreadPoolExecutor, Queuing; Rejected tasks
  8. Asynchronous Programming in Rust, Build an Executor, introduction
  9. Asynchronous Programming in Rust, The Async Ecosystem, Async Runtimes
  10. Python documentation, asyncio Event Loop, loop.run_in_executor
  11. Microsoft Learn, ConcurrentExclusiveSchedulerPair class, class description
  12. MDN Web Docs, Using microtasks in JavaScript with queueMicrotask, Tasks vs. microtasks
  13. Go FAQ, Why goroutines instead of threads?
  14. Go by Example, Worker Pools, whole page
  15. cppreference, std::async, Async invocation; Deferred invocation; Policy selection
  16. Wikipedia, Java version history, J2SE 5.0

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/EHE1JZ/text.yaml