可以监控STM的争用级别吗?

时间:2013-06-18 08:48:11

标签: clojure stm

有没有办法来评估Clojure的STM交易是否正在重试,以及以什么速度进行?

3 个答案:

答案 0 :(得分:2)

您可以观察参考的history count,表明存在争用:

user=> (def my-ref (ref 0 :min-history 1))
#'user/my-ref
user=> (ref-history-count my-ref)
0
user=> (dosync (alter my-ref inc))
1
user=> (ref-history-count my-ref)
1

历史记录计数不直接代表争用。相反,它表示为维护并发读取而维护的过去值的数量。

历史记录的大小受minmax值的限制。默认情况下,它们分别为010,但您可以在创建ref时更改它们(请参见上文)。由于min-history默认为0,因此您通常不会看到ref-history-count返回非零值,除非参考号存在争用。

在此处查看有关history count的更多讨论:https://groups.google.com/forum/?fromgroups#!topic/clojure/n_MKCoa870o

我认为clojure.core提供的任何方式都没有办法观察目前STM交易的速度。你当然可以做类似于@Chouser在history stress test中所做的事情:

(dosync
    (swap! try-count inc)
    ...)

即。在交易中增加一个计数器。每次尝试交易时都会发生增量。如果try-count大于1,则会重试该交易。

答案 1 :(得分:2)

通过引入命名的dosync块提交计数(命名的dosync成功的次数),可以很容易地跟踪线程重试给定事务的时间

(def ^{:doc "ThreadLocal<Map<TxName, Map<CommitNumber, TriesCount>>>"}
  local-tries (let [l (ThreadLocal.)]
                (.set l {})
                l))

(def ^{:doc "Map<TxName, Int>"}
  commit-number (ref {}))

(def history ^{:doc "Map<ThreadId, Map<TxName, Map<CommitNumber, TriesCount>>>"}
  (atom {}))

(defn report [_ thread-id tries]
  (swap! history assoc thread-id tries))

(def reporter (agent nil))

(defmacro dosync [tx-name & body]
  `(clojure.core/dosync
    (let [cno# (@commit-number ~tx-name 0)
          tries# (update-in (.get local-tries) [~tx-name] update-in [cno#] (fnil inc 0))]
      (.set local-tries tries#)
      (send reporter report (.getId (Thread/currentThread)) tries#))
    ~@body
    (alter commit-number update-in [~tx-name] (fnil inc 0))))

鉴于以下示例......

(def foo (ref {}))

(def bar (ref {}))

(defn x []
  (dosync :x ;; `:x`: the tx-name.
          (let [r (rand-int 2)]
            (alter foo assoc r (rand))
            (Thread/sleep (rand-int 400))
            (alter bar assoc (rand-int 2) (@foo r)))))

(dotimes [i 4]
  (future
   (dotimes [i 10]
     (x))))

... @history评估为:

;; {thread-id {tx-name {commit-number tries-count}}}
{40 {:x {3 1, 2 4, 1 3, 0 1}}, 39 {:x {2 1, 1 3, 0 1}}, ...}

答案 2 :(得分:0)

这种额外的实施方式非常简单。

;; {thread-id retries-of-latest-tx}
(def tries (atom {}))

;; The max amount of tries any thread has performed
(def max-tries (atom 0))

(def ninc (fnil inc 0))

(def reporter (agent nil))

(defn report [_ tid]
  (swap! max-tries #(max % (get @tries tid 0)))
  (swap! tries update-in [tid] (constantly 0)))

(defmacro dosync [& body]
  `(clojure.core/dosync
    (swap! tries update-in [(.getId (Thread/currentThread))] ninc)
    (commute commit-id inc)
    (send reporter report (.getId (Thread/currentThread)))
    ~@body))