Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure STM ambiguity factor

Tags:

clojure

stm

In Clojure we use STM for Concurrency.

My question is STM uses point in time value of data , isn't this introduce ambiguity ?

How could we know what value is accessed ?

like image 269
nish1013 Avatar asked Dec 15 '22 09:12

nish1013


1 Answers

The STM in Clojure provides (through refs and dosync) a transaction context where all updates are guaranteed to be made "at the same time" to all the refs involved when viewed from the outside world.

The objective is to maintain consistency of the values in the system, the typical example is the transfer of money between two bank accounts. If you are transferring, say, 100 dollars from account A to account B, then you'll want to have the amounts for A and B changed simultaneously.

In this example there's actually no ambiguity in the values read for the amounts that are being handled inside the transaction, because only the following situations are possible at the moment the read from outside the transaction is done:

  1. The transaction has begun but is not yet finished, so the values have not been "officially" changed. The transaction can later be committed or retried, but when you read them, that was the state of each account.
  2. The transaction has finished so the amounts read are the modified values.

When inside the transaction, the refs you only read (and don't modify) could change their value from one point of the transaction to the other, this is called write skew (see Clojure Programming - Chapter 4, Refs, Write Skew). In order to avoid this you can use ensure (instead of deref), this will cause that if the value for any of these refs changes (the ones you only read), then the whole transaction will be retried.

like image 91
juan.facorro Avatar answered Jan 28 '23 04:01

juan.facorro