As much as I like Clojure and atoms, I do not think they are a good fit for 
caching. Not only is it impossible to address the concurrency issues 
related to multiple threads loading the same object, but you also have to 
do expiration and size management yourself. Immutability doesn't help much 
for caching either. There is core.cache that does some bits but I probably 
would recommend using something like CacheBuilder from the guava libs:

See
https://code.google.com/p/guava-libraries/
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/CacheBuilder.html

Its Java but the Clojure<->Java interop is so good that it doesn't matter 
much.

On Saturday, August 30, 2014 7:27:05 AM UTC+2, Colin Fleming wrote:
>
> Hi all,
>
> I want to use a map to cache values based on a key. I'm planning to use an 
> atom for this. My basic operation is "give me the value for this key" - if 
> the value exists in the map then that value should be returned, otherwise a 
> new value should be calculated, inserted in the map and then returned. My 
> plan is to implement something like the following:
>
>
> (defn ensure [cache key]  (if (contains? cache key)    cache    (assoc cache 
> key (calc-value key))))(let [value (get (swap! cache ensure key) key)]  ... 
> do my thing with value ...)
>
>
> So 'ensure' ensures that the cache contains the value for key, the swap! 
> operation returns the cache with the value and then I get it out. This 
> works but feels a little clumsy, is there a better way to do this?
>
> Also, looking at the Atom source code, I see that this will cause a CAS 
> operation even if the value returned from swap! is identical to the 
> original value. It seems like a reasonable optimisation would be to check 
> if the values are identical and not update if so - is there a reason this 
> might not be a good idea?
>
> Thanks,
> Colin
>

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