Can I access Clojure's STM value history?

Given that STM contains a history of, say, 10 ref values, agents, etc., can these values ​​be counted?

The reason is that I am updating the agent load and I need to keep a history of values. If STM saves them already, I would rather use them. I can’t find functions in the API that look like they are reading values ​​from the STM history, so I’m not sure and cannot find any methods in the java source code, but maybe I didn’t look right.

+7
source share
1 answer

You cannot directly access the STM value history. But you can use add-watch to record the history of values:

(def a-history (ref [])) (def a (agent 0)) (add-watch a :my-history (fn [key ref old new] (alter a-history conj old))) 

Each time a updated (transaction stm is committed), the old value will be associated with the sequence stored in a-history .

If you want to access all intermediate values, even for rollback transactions, you can send values ​​to the agent during the transaction:

 (def r-history (agent []) (def r (ref 0)) (dosync (alter r (fn [new-val] (send r-history conj new-val) ;; record potential new value (inc r)))) ;; update ref as you like 

After the transaction is completed, all changes to the r-history agent will be made.

+9
source

All Articles