Apama 10.15.2 | Developing Apama Applications | Developing Apama Applications in EPL | Implementing Parallel Processing | Samples for implementing contexts | About the compareswap sample
 
About the compareswap sample
This compareswap sample is more like the race sample. The protocol between tellers and the database consists of Get and Set events, except the Set event is a CompareSet event, which contains an expected old value. If the old value does not match the database account value, then the teller retries the operation — getting a new value and re-computing the account value.
This has the advantage that it does not rely on locking (so does not suffer from deadlock) and does not result in values computed from out of date data being set in the database.
The only disadvantage is that under some circumstances (the same as for the race sample), the tellers need to re-try a calculation. However, unlike the timeout on locking, tellers know about this as soon as they receive an event back from the database, and no timeouts are involved.
This strategy is the recommended way to share state between different contexts. Note that while it guarantees progress is made by at least one context, an interaction between the database and a single context can take an unbounded amount of time, as other contexts can require the context to re-try its transaction. A further refinement would be to use a generation counter that the correlator increments on every successful Set event. This detects the difference between the database's value being unchanged and the database's value being changed back to a previous value. While such a difference might not matter in many situations, it might when you are computing interest.
Note: 
Due to the requirement to retry, the compareswap implementation is slightly different from the race implementation. One account is modified at a time; the teller transfers money from the fromAccount, and then adds it to the toAccount.
Time
Teller 1
Teller 2
Bank Database
0 (setup)
Transfer 50 from A to B
A: 100 B: 100 C: 100
Get A
A=100
newA=50
A: 50, B: 100, C:100
Set A success
Get B
B = 100
Sleep 1
0.5
Transfer 25 from B to C
Get B
B=100
newB=75
Set B (old=100)
A: 100, B: 75, C: 100
Set B success
Get C
C=100
newC=125
Set C (old=100)
A: 50, B: 75, C: 125
Set C success
1.0
newB = 150
Set B (old=100)
A: 50, B: 75, C: 125
Set B FAILED
Get B
B = 75
newB = 125
Set B (old=75)
A: 50, B: 125, C: 125
Set B success