Stm and change in clojure

I work through the Clojure programming book. Explaining alter and STM, they say that if during alter, Clojure detects a change in ref from an external transaction, it will restart the transaction with the new value. If so, I would suggest that the update function you pass in should be clean, but this is not stated in the docs (and in other similar situations).

So is my assumption true? If not, how does STM reapply this feature? If this is correct, is it not so that you cannot rely on documents to tell you when you can have side effects and when you cannot?

+4
source share
3 answers

It is not necessary to be clean, it must be idempotent . In practice, this is basically the same.

In addition, it should only be idempotent when viewed outside of the STM: if the only side effect that you produce is recorded in some other link or (I think) sending to the agent, this operation will be carried out as long as your transaction will not succeed.

It is also not that it should be any of these things: simply, if your update function is not clean, the results may not be what you expect.

Edit: dosync docs tell you that any expressions in the body can be executed more than once. You cannot start alter without running dosync , so it looks as if you have all the documents you need. What would you like to change?

+8
source

As a note:

If you need to perform side effects such as logging in your STM transaction, you can send messages to agents to perform non-idempotent parts. Messages sent to agents are only sent when the transaction is completed and is expected to be sent only once.

+4
source

The point in Clojure is that when dealing with transactions there is no side effect, since they are consistent with each other, and the function will restart (I prefer to try again) when it detects a conflict during the Shared value update, otherwise it will result to a successful change. If he should try again, he will read the updated value, so there is no side effect, the problem you can find is Livelock, but it is controlled by the number of prefix in the repetitions from Clojure.

+1
source

Source: https://habr.com/ru/post/1345182/


All Articles