【发布时间】:2013-04-28 17:35:56
【问题描述】:
受this Event Sourcing 博文的启发,我想知道是否可以实现与 Java ConcurrentHashMap 等效的 Clojure 结构。基础this Rich 发布到 Clojure maling 列表中,我提出了以下部分实现,但我不确定它是否是并发安全的?如果不是,任何人都可以提出更好的方法来构建这样的结构吗?
(defn ^M h []
(let [m (atom {})]
(reify M
(put [_ k v] (swap! m assoc k v))
(get [_ k] (get @m k))
(putIfAbsent [_ k v]
(swap! m #(if (get % k)
%
(assoc % k v))))
(replace [_ k old-v new-v]
(swap! m #(if (= old-v (get % k))
(assoc % k new-v)
%))))))
(definterface M
(put [k v])
(get [k])
(putIfAbsent [k v])
(replace [k old-v new-v]))
参考资料:
http://www.jayway.com/2013/04/02/event-sourcing-in-clojure/
https://groups.google.com/d/msg/clojure/dK6x_QpCpvo/OitIryoFSAgJ
【问题讨论】:
标签: java concurrency clojure concurrenthashmap