liveBook · Manning

*agent*

As explained in Clojure: The Essential Reference

*agent* is a Clojure dynamic variable bound to the agent whose action function is currently executing.

*agent* is a Clojure dynamic variable that is automatically bound to the agent whose action function is currently executing. Outside an agent action, it is nil. section 23.3

Use *agent* when an action needs to refer back to its own agent, especially for recursive scheduling with send or send-off. The binding identifies the current agent rather than requiring that agent to be passed as an argument. section 14.6 section 23.3

Confirming the current agent

(def a (agent 10)) (send a #(do (println (identical? *agent* a)) (inc %))) ;; true (println *agent*) ;; nil

Self-scheduling action

(defn ping [{:keys [kill] :as state}] (when-not kill (send-off *agent* ping)) state) (send-off a ping)

(println "Is there an *agent*?" *agent*)
;; Is there an *agent*? nil ; #1

(send
  (agent 10)
  (fn [value]
    (Thread/sleep 1000) ; #2
    (println "Is there an *agent*?" (deref *agent*))))
;; #object[clojure.lang.Agent 0x1ff5d0e {:status :ready, :val 10}]
;; Is there an *agent*? 10 ; #3

Compare the nil binding outside an agent action with the current agent instance observed during action execution. section 23.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines automatic binding and demonstrates identity and nil behavior, but defers broader agent error and scheduling semantics.
Examples
Uses nil outside an action, identity comparison inside an action, and recursive ping scheduling.
What it assumes
Assumes familiarity with Clojure agents, action functions, dynamic variables, send, and send-off.
What you can do after
Apply it to let agent actions reschedule themselves without receiving the agent as an explicit argument.
How it connects
Connects dynamic variables with agents, action functions, send, and send-off.

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.