【问题标题】:What's the right way to initialize resources in a multi-threaded program in ClojureClojure多线程程序中初始化资源的正确方法是什么
【发布时间】:2016-09-16 21:29:47
【问题描述】:

我知道组件和系统(虽然没有使用它们),但我想知道当 init 方法可以从任何线程运行时如何初始化资源。假设我们有 10 个线程,它们都使用 db,并且线程可以按任意顺序启动。这种情况下如何初始化db连接池?

我目前使用比较和设置来执行此操作,但不知何故感觉不对。 我就是这样做的。

(let [datasource (atom nil)]
  (defn pooled-conn
    "Get a Hikari pooled connection to the database. There will only be one
  connection pool for the vm. Additional calls to this function will return
  the same connection pool. The connection pool will be created by the first
  call to this function"
    [datasource-options]
    (when (nil? @datasource)
      (let [ds (make-datasource datasource-options)]
        (when-not (compare-and-set! datasource nil {:datasource ds})
          (close-datasource ds))))
    @datasource))

我不知道 vm 何时启动,就在我的线程启动时(我正在使用storm,db pool 在某些螺栓中初始化)。有没有更好的方法来做到这一点?

【问题讨论】:

  • 您提到了组件和系统,您也可以查看mount 以获得更自然的clojure 感觉。
  • 看起来很酷@Shlomi,会去看看

标签: multithreading clojure apache-storm


【解决方案1】:

您想使用locking 函数。就像 Java 中的 synchronized

请在此处查看完整文档:http://clojuredocs.org/clojure.core/locking

您的代码将类似于:

(def datasource (atom))
(locking datasource
  (when (nil? @datasource))
    (reset! datasource (make-datasource datasource-options))))

请注意,您实际上并不需要原子内部的地图。

【讨论】:

  • 看起来好多了。谢谢!
猜你喜欢
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 2020-02-15
相关资源
最近更新 更多