What is the shutdown-agents method in Clojure?

What is an agent in Clojure?

Clojure variables are immutable, but with the use of an agent, the storage location can be mutated alongside the use of functions. The changed state of the agent is then returned, as we'll see in the example below.

What is the shutdown-agents method?

The shutdown-agents method is used to stop all running agents in a code because agents make use of state and are continuously active.

Syntax

(shutdown-agents)
Syntax of the shutdown-agents method

Parameters

The shutdown-agents method receives no parameter.

Return value

The shutdown-agents method has no return value as it is like a switch used to stop active agents.

(ns clojure.examples.example
(:gen-class))
(defn func []
(def names (agent 10))
(println @names)
(send names + 200)
(await-for 50 names)
(println @names)
(shutdown-agents))
(func)

Explanation

  • Line 3: We define a function func.

  • Line 4: We define a names variable with the agent method and we set the agent state to 10.

  • Line 5: We print the names variable.

  • Line 6: We use the send method to change the value of the names variable.

  • Line 7: We use the await-for method to cause a delay of 50 seconds so that the send method executes properly since it takes time to process.

  • Line 8: We print the variable names. Note that the names variable is now 210 instead of 10 because of the help of the send method.

  • Line 9: When we now call the shutdown-agents method all the agents are stopped. If not, an error will be thrown. You can try removing the line with the shutdown-agents code.

  • Line 10: We call the function func.

Free Resources