How can I stop a specific agent in Clojure? When do their states collect garbage?

If an agent runs through a background turn in Clojure, how can I stop it without stopping all agents?

When I finish with the agent, and I let him fall out of the area. And he finishes work on his lineup, is it garbage collection along with his final state?

+6
clojure agents
source share
1 answer

manage agents as data not flows

An agent is a data structure associated with a thread pool and an event queue. when events are available for agents, then the threads in this pool take turns working with the agents until the thread pool is full or the event (work) queue becomes empty. the agent collects garbage when the last link to it goes beyond.

if you bind the top level of var to it, it will stick forever.

(def foo (agent {})) 

if you bind it to a name in a function, it will be GCd at the end of this function

 (defn foo [] (let [foo (agent {})] (send do-stuff foo))) 

I do not see a direct message about the cancellation of the agent work queue, although you can hack this by installing a validator on the agent, which always returns false . This can cause the agent to stop working and wait for the agent error to be deleted.

if you want to kill an agent from code outside the lexical area in which the agent was created, you will need to save the agent in some mutable structure, for example, for an atom, so that you can remove the link to the agent so that it is a GCD.

 (def my-agent (atom nil)) ;a persistent name for a transient agent (swap! my-agent (make-new-agent)) ;create the agent (send do-stuff @my-agent) ;use the agent (swap! my-agent nil) ;clean up 
+5
source share

All Articles