Clojure – Agents

Clojure agents

In this guide, we will discuss Clojure Agents. As pointed out many times, Clojure is a programming language wherein many of the data types are immutable, which means that the only way one can change the value of a variable is to create a new variable and assign the new value to it. However, Clojure does provide some elements, which can create an mutable state. We have seen that this can be achieved with the atom data type. The other way this can be achieved is via Agents.

Agents provide independent, asynchronous change of individual locations. Agents are bound to a single storage location for their lifetime, and only allow mutation of that location (to a new state) to occur as a result of an action. Actions are functions (with, optionally, additional arguments) that are asynchronously applied to an Agent’s state and whose return value becomes the Agent’s new state.

The following operations are possible in Clojure with regards to Agents.

Sr.No.Operations & Description
1agent
An agent is created by using the agent command.
2send
This function is used to send across a value to the agent.
3shutdown-agents
This function is used to shut down any running agents.
4send-off
There are instances wherein an agent is assigned a function which is blocking in nature.
5await-for
Since there is a delay when a value of an agent is updated, Clojure provided a ‘await-for’ function which is used to specify time in milliseconds to wait for the agent to be updated.
6await
Blocks the current thread (indefinitely!) until all actions dispatched thus far, from this thread or agent, to the agent(s) have occurred. Will block on failed agents.
7agent-error
Returns the exception thrown during an asynchronous action of the agent, if the agent fails. Returns nil if the agent does not fail.

Next Topic : Click Here

This Post Has One Comment

Leave a Reply