liveBook · Manning

Thread pool

As explained in Clojure: The Essential Reference

A thread pool is a set of reusable worker threads managed to execute multiple tasks without creating a new thread for each task.

A thread pool provides reusable worker threads for executing multiple tasks without creating a new thread for each task. In Clojure concurrency, agents and futures share a pool, while workload-specific dispatch can use a separate executor. section 14.6

Use thread-pool controls to match execution behavior to the workload:

  • Send ordinary agent actions with send; use send-off when an action may keep a thread busy for a long time. section 14.6
  • Route an action through a chosen executor with send-via, or replace the agent send executors globally with set-agent-send-executor! and set-agent-send-off-executor!. section 14.6
(import '[java.util.concurrent Executors])

(def fj-pool (Executors/newWorkStealingPool)) ; #1

(defn send-fj [^clojure.lang.Agent a f & args]
  (apply send-via fj-pool a f args)) ; #2

(def a (agent 1)) ; #3
(send-fj a inc)
(await a)
@a

A custom work-stealing pool can dispatch an agent action through send-via while preserving the agent’s ordered state updates. section 14.6

(import '[java.util.concurrent Executors])

(def fj-pool (Executors/newWorkStealingPool 100)) ; #1

(set-agent-send-executor! fj-pool) ; #2
(set-agent-send-off-executor! fj-pool)

The same executor can be installed for both regular agent sends and send-off actions. section 14.6

How Clojure: The Essential Reference covers it

How deep it goes
Defines shared and configurable execution pools, but stops short of explaining worker scheduling internals.
Examples
Demonstrates a work-stealing executor, send-via dispatch, and global agent executor replacement.
What you can do after
Operate/configure agent execution with send-via or custom Executors.
How it connects
Ties thread pools to agents, futures, executors, and STM transactions.

Also explained in

Compare how 10 books explain thread pool →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.