Hi,

Am Donnerstag, 21. November 2013 11:19:54 UTC+1 schrieb Jim foo.bar:
>
>  On 20/11/13 19:36, juan.facorro wrote:
>  
> The value for all refs whose value you don't actually modify inside a 
> transaction should be obtained through 
> ensure<http://clojuredocs.org/clojure_core/clojure.core/ensure>
>  if you want to make sure :P their value won't be changed by a different 
> transaction, that way you get a consistent value when the current 
> transaction is finally committed. 
>
>
> ok this is an interesting and relevant for me comment....let's take a step 
> back. Assume the same bank from my previous example and consider the 
> following function:
>
> (defn total! 
>  "Sum all accounts safely with a consistent view even if other 
> transactions are still running."
>  [bank]
>    (dosync
>      (reduce +'
>        (map (comp :curr-balance second) *@bank*))))
>
> What would be the implications of changing the bold bit to *(ensure bank) 
> *?
>
>
For this you don't even need a transaction. As long as you bank doesn't 
contain other refs, this is perfectly fine. With the deref you get a 
snapshot.

ensure is only needed when you want to change a ref based on the value of 
another ref, but you only read the other ref. See this example:

(defn maybe-launch-rockets!
  [defcon command-queue]
  (dosync
    (when (= :war (ensure defcon))
      (alter command-queue conj :launch-rockets))))

Here you change command-queue purely based on the value of defcon without 
modifying defcon. Then you have to use ensure to get a consistent view of 
both refs. Without using ensure, you might get the following situation:

1. Your transaction starts.
2. You read defcon.
3. A peace treaty is signed and another transaction resets defcon to :peace.
4. You schedule the rocket launch based on a now bogus defcon value.
5. Your transaction commits, because you did not modify defcon and thusly 
don't get a conflict.
6. 3rd world war ensues.

ensure declares your interest in defcon. You get a conflict and the above 
cannot happen. (In fact: you block the peace treaty negotiations until the 
rockets are launched, but that is an implementation detail.)

Hope that helps.

Meikel

-- 
-- 
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/groups/opt_out.

Reply via email to