2016-09-16 2 views
3

私はコンポーネントとシステムを認識していますが、まだ使用していませんが、initメソッドを使用してリソースを初期化する方法を知っています任意のスレッドから実行できます。私たちが10のスレッドを持っていて、すべてがdbを使用し、スレッドが任意の順序で開始できるとしましょう。このような場合、db接続プールをどのように初期化するのですか?Clojureのマルチスレッドプログラムでリソースを初期化する正しい方法は何ですか?

私は現在、これを行うために比較と設定を使用していますが、どういうわけか、それは正しいと感じません。 これは私が行うことです。

(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)) 

私のスレッドが起動するとき(私は嵐を使用しています、dbプールはいくつかのボルトで初期化されています)の起動時を知りません。これを行うより良い方法はありますか?

+1

あなたはコンポーネントとシステムについて言及していますが、より自然なクローゼット感覚を得るために[mount](https://github.com/tolitius/mount)をチェックすることもできます。 – Shlomi

+0

涼しい@Shlomiを見て、それをチェックします – Ravi

答えて

3

locking機能を使用します。 Javaの場合は​​です。

ここに完全なドキュメントを参照してください:http://clojuredocs.org/clojure.core/locking

あなたがコードしているが、その後のようになります。あなたが本当に原子内部のマップを必要としない

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

注意を。

+0

ははるかに良い見えます。ありがとうございました! – Ravi

関連する問題