This part covers the concurrent parts of ZIO including STM, fiber, queue, promise, and semaphore. It is based on the video Atomically {delete your actors}.
1 STM
STM is Software Transactional Memory. It provides the ability to atomically commit a series of reads and writes to transactional memeory where a set of conditions is satisfied. STM retries when the conditions are not met and rollbacks when there is a concurrent change.
STM[E, A]
is a transaction which models reads and writes and can fail, retry or suceed. TRef[A]
is a transactional reference to an immutable value, which is read and written inside STM transactions. STMs are composable.
|
|
STM has map
, flatMap
, succeed
, fail
, fold
, foldM
, retry
(asynchronously and atomatically retry), zip
, check
(suspend if condition is not satisfied), filter
(check
and return), orElse
, collect
(filter
and map
).
2 Sample Implementation of Semaphore, Promise and Queue
|
|
3 Concurrency Data Types
3.1 Semaphore
Use Semaphore.make(permits=count)
to create a semaphore with specified permits and use Semaphore#withPermit(count)(effect)
to run an effect when the requried permits are acquired.
3.2 Promise
A Promise[E, A]
is a variable of IO[E, A]
type that is set exactly once. It is often used by fibers to pass values to each other. Promise.make[E, A]
returns UIO[Promise[E, A]
that is a description of the promise creation. A promise should be created inside IO.
A promise can be completed by the following methods:
succeed
: succeed with a value of typeA
done
: succed withExit[E, A]
complete
: execute an effect once and the result will be propagated to all waiting fiberscompleteWith
: execute an effect for each of the waiting fiberfail
: fail with an error typeE
die
: defect withThrowable
halt
: fail withCause[E]
interrupt
: interrupt
The completion of a promise result in an UIO[Boolean]
that represents whether the value has been set ture
or was already set false
.
Other methods include await
to wait and get result, poll
to get without wait, isDone
check if it is completed.
3.3 Queue
The ZIO Queue
is composable, transparent back-pressure, asynchronous (no locks or blocking), purely-functional and type-safe. It has tow basic operations: offer
and take
. A queue can be unbounded Queue.unbounded
or bounded. For bounded, it could be blocking Queue.bounded
, drop new Queue.dropping
, drop old Queue.sliding
.
Other operations include offerAll
, takeUpTo
, takeAll
, poll
, shutdown
, awaitShutdown
.
Use ZQueue
to transform queues. The methods are map
, mapM
, contramapM
, bothWith
.