Cats STM

Cats STM

  • Docs
  • API
  • GitHub

›Theory

Overview

  • Getting started

Theory

  • Introduction
  • Txn
  • TVar

Data Types

  • TMVar
  • TQueue
  • TSemaphore

Worked Examples

  • The Santa Claus Problem

TVar

A TVar (transactional variable) is a mutable memory location that can be be read and modified via Txn actions.

import cats.effect.IO
import cats.effect.unsafe.implicits.global
import io.github.timwspence.cats.stm.STM

val stm = STM.runtime[IO].unsafeRunSync()
// stm: STM[IO] = io.github.timwspence.cats.stm.STM$Make$$anon$1$$anon$2@2ecbcfeb
import stm._

val to   = stm.commit(TVar.of(1)).unsafeRunSync()
// to: TVar[Int] = io.github.timwspence.cats.stm.STMLike$TVar@13fd88d7
val from = stm.commit(TVar.of(0)).unsafeRunSync()
// from: TVar[Int] = io.github.timwspence.cats.stm.STMLike$TVar@24b3e5a8

val txn: Txn[(Int, Int)] = for {
  balance <- from.get
  _       <- from.modify(_ - balance)
  _       <- to.modify(_ + balance)
  res1    <- from.get
  res2    <- to.get
} yield res1 -> res2
// txn: Txn[(Int, Int)] = Bind(
//   txn = Get(tvar = io.github.timwspence.cats.stm.STMLike$TVar@24b3e5a8),
//   f = <function1>
// )

val result = stm.commit(txn).unsafeRunSync()
// result: (Int, Int) = (0, 1)

Note that this does not modify either from or to!! It merely describes a transaction which must be executed via STM#commit

← TxnTMVar →
Docs
Getting startedExamples
Community
BlogGitter
More
Star
Follow @TimWSpence
Copyright © 2018-2022 Tim Spence