Changes to STM in Effect 4
STM (Software Transactional Memory) is a way to manage concurrent modifications of shared state through transactions, roughly similar to database transactions. Let's say we need to transfer money from one account to another: we need to deduct the amount from one account and add it to the other. Playground — Effect v3 // Effect v3 const program = Effect . gen ( function * () { const alice = yield…
In Effect v3, STM (Software Transactional Memory) operates separately from Effect computations. It is synchronous and pure, meaning it cannot be interrupted during execution. When modifying shared state through transactions, STM maintains a journal of interactions with TRefs, storing a reference to the ref, its initial value, and its current value within the transaction.
Upon calling STM.commit, STM checks if the original TRef values remain unchanged. If valid, the changes are applied; otherwise, the transaction restarts. STM's purity allows it to continue until successful commit. However, Effect computations cannot be used inside STM computations, leading to challenges in logging and debugging.
Effect v4 streamlines this by integrating STM directly into Effect. The Tx* modules replace STM, utilizing Effect.Transaction to manage transactions. This change enables STM computations to be represented at the type level with Transaction, similar to managing resources with Scope. Effect.Transaction operates implicitly, attached to existing transactions within the context, allowing multiple Tx* operations to be encompassed within a single transaction boundary.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.