Taming the Concurrency Crocodile
What is the problem?
At the most basic level every business process being executed on a computer program can be distilled down to two parts:
1) Get the current state of something
2) Do some action based on that current state
However in a distributed system that process will take an amount of time (t)
During that time it is possible that some other action will have occurred such that the state being acted upon has changed (or is no longer the current state). If this leads to a system being in an inconsistent state you have a type of defect known as a concurrency crocodile.?
Transactions
The most common solution to this is to wrap the two steps in an atomic transaction
Most database solutions work this way and this has been the standard way to solve this for the majority of situations. On a single machine, transactions are a stable and solved problem but things do get a lot more difficult when you need to do transactions across heterogeneous and distributed systems.
Locks
Locks are a very similar solution to transactions - whenever a process wants to act on a state in a way that it would alter that state it must first acquire a lock (or token) and once it has succeeded it must release that lock. This prevents the state changing which means that the t factor can be ignored.
Locks are a less stable solution than transactions because if a process fails to release the lock it may remain locked forever. For this reason locks are usually implemented with a timeout or with a manual override process.
Undo on conflicts
Another way to address a concurrency conflict is to check after you have acted on the state that the state is still valid and, if not, to undo the action. Doing this does require careful design to make sure that all such actions are reversible but if the frequency of conflict are low this can result in a faster overall system.
Act on prior state
It is also possible to eliminate the impact of t by explicitly making your updates occur on a known prior state.
In a system where the prior state is immutable this is a safe way of avoiding any concurrency issues but again this requires careful design of the business rules to acknowledge the fact that they operate on prior state and that this does not lead to unintended consequences.