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

有没有什么方法可以调查Clojure的STM交易是否正在重试以及以何种速度进行?


你可以观察到一个ref的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返回非零值,除非ref上存在争用。

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

我认为clojure.core没有任何办法来观察STM交易的速度。 当然,你可以做一些类似于@Chouser历史压力测试的东西:

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

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


通过引入命名的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}}, ...}

这个额外的实现要简单得多。

;; {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))
链接地址: http://www.djcxy.com/p/71991.html

上一篇: Can one monitor STM's contention level?

下一篇: Implementing Incompatible Interfaces