Clojure - Agents


Advertisements

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
1 agent

An agent is created by using the agent command.

2 send

This function is used to send across a value to the agent.

3 shutdown-agents

This function is used to shut down any running agents.

4 send-off

There are instances wherein an agent is assigned a function which is blocking in nature.

5 await-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.

6 await

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.

7 agent-error

Returns the exception thrown during an asynchronous action of the agent, if the agent fails. Returns nil if the agent does not fail.

Advertisements