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)
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
namesvariable with theagentmethod and we set the agent state to10.Line 5: We print the
namesvariable.Line 6: We use the
sendmethod to change the value of thenamesvariable.Line 7: We use the
await-formethod to cause a delay of50seconds so that thesendmethod executes properly since it takes time to process.Line 8: We print the variable
names. Note that thenamesvariable is now210instead of10because of the help of thesendmethod.Line 9: When we now call the
shutdown-agentsmethod all the agents are stopped. If not, an error will be thrown. You can try removing the line with theshutdown-agentscode.Line 10: We call the function
func.