STM provides a concurrency-control mechanism for managing access to shared memory. STM makes use of two concepts – optimism and transactions to manage the shared concurrency control.
- Optimism means that we run multiple atomic blocks in parallel, assuming there will be no errors. When we are done, we check for any problems. If no problems are found, we update the state variables in the atomic block. If we find problems then we roll back and retry. Optimistic concurrency typically provides better scalability options than any other alternate approaches.
- Secondly, STM is modeled on similar lines of database transaction handling. In the case of STM, the Java heap is the transactional data set with begin/commit and rollback constructs. As the objects hold the state in memory, the transaction only implements the following characteristics – atomicity, consistency, and isolation.
Akka transactors are based on CommitBarrier, where the atomic blocks of each actor (member) participating are treated as one, big single unit. Each actor will block until everyone participating in the transaction has completed. This means that all the actions executed as part of the atomic blocks by members of the CommitBarrier will appear to occur as a single atomic action even though the members may be spread across multiple threads. If any of the atomic blocks throw an exception or a conflict happens, all the CommitBarrier members will roll back.
Money transfer between two accounts
To make sure that the money transfer in the account happens in a synchronized way, we need to implement the following:
- In the account object, the state variable that needs to participate in the transaction should be of transaction reference type.
- The credit and debit operations in the account object need to be atomic.
- In the transfer object, the transaction boundary needs to be defined and the account objects need to participate in the same transaction context.
- In addition, we define the supervisor policy in TransferActor and BankActor to handle the transaction exceptions:
Parts of the post are excerpts from the book - Akka Essentials. For more details on the example, please refer to the book.