Oh, and as for how to use it here, you could for example say

  (.putIfAbsent concurrent-hash-map :foo (delay (foo)))

Then the first thread to @(get concurrent-hash-map :foo (delay
:not-found)) (or similar) would actually compute the value.

With a map in an atom, you could swap! using a function like

  (fn [old-state]
    (if (contains? old-state :foo)
      (assoc old-state :foo (delay (foo)))
      old-state))

I'd probably prefer a CHM for this purpose, though.

Michał


On 8 December 2014 at 21:33, Michał Marczyk <michal.marc...@gmail.com> wrote:
> On 8 December 2014 at 17:54, Andy L <core.as...@gmail.com> wrote:
>>> But I'd personally just use a delay rather than "locking" for this
>>> purpose.
>>
>>
>> It is not that I like locking at all. However I still fail to see, how in a
>> multithreaded context memoize/cache prevents executing a given function more
>> than once (which I want to avoid at any cost here) since cache lookup and
>> swap! does not seem to be atomic :
>> https://github.com/clojure/core.cache/blob/master/src/main/clojure/clojure/core/cache.clj#L52
>
> When you say
>
>   (delay (foo)),
>
> foo will be called at most once, regardless of how many times you
> deref (@) / force the delay. (If you never force the delay, it will
> not be called at all.) The way this is enforced is through making
> deref a synchronized method on delays.
>
> Cheers,
> Michał

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to