鉴于 STM 拥有 10 个 refs、agents 等值的历史记录,可以读取这些值吗?
原因是,我正在更新大量代理,并且需要保留值的历史记录。如果 STM 已经保留了它们,我宁愿只使用它们。我在 API 中找不到看起来像是从 STM 历史中读取值的函数,所以我猜不是,我也无法在 java 源代码中找到任何方法,但也许我看起来不对。
您不能直接访问值的 stm 历史记录。但是你可以使用add-watch来记录值的历史:
(def a-history (ref []))
(def a (agent 0))
(add-watch a :my-history
(fn [key ref old new] (alter a-history conj old)))
每次a
更新(stm 事务提交)时,旧值将被转换到保存在a-history
.
如果您想访问所有中间值,即使对于回滚事务,您也可以在事务期间将值发送给代理:
(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
事务完成后,r-history
将执行对代理的所有更改。