Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Clojure's STM's history of values be accessed?

Given that the STM holds a history of say 10 values of refs, agents etc, can those values be read ?

The reason is, I'm updating a load of agents and I need to keep a history of values. If the STM is keeping them already, I'd rather just use them. I can't find functions in the API that look like they read values from the STM history so I guess not, nor can I find any methods in the java source code, but maybe I didn't look right.

like image 227
Hendekagon Avatar asked Jun 27 '11 04:06

Hendekagon


1 Answers

You cannot access the stm history of values directly. But you can make use of 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)))

Every time a is updated (the stm transaction commits) the old value will be conjed onto the sequence that is held in a-history.

If you want to get access to all the intermediary values, even for rolled back transactions you can send the values to an 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 finished, all changes to the agent r-history will be executed.

like image 180
ordnungswidrig Avatar answered Sep 30 '22 02:09

ordnungswidrig