# sicp-ex-3.43

timothy235

Double serializing the exchange procedure, using both accounts' serializers, protects the exchange operations from being interleaved with other account operations from either account. This makes exchange atomic. So its behavior will be as expected.

With the original definition of exchange, the exchange operation will not be atomic, but it will be composed of exactly four atomic operations, namely read the two account balances, make an atomic withdrawal from the larger account, and make an atomic deposit into the smaller account.

To see how the original exchange definition might not preserve the three balances, consider the following three exchanges:

• acct1 = 10
• acct2 = 20
• acct3 = 30
• P1: exchange accounts 1 and 2
• P2: exchange accounts 2 and 3
• P3: exchange accounts 1 and 3

The original exchange allows us to interleave P3 between reads of P1 and P2:

• P1 reads acct1 = 10
• P2 reads acct2 = 20
• P3 makes acct1 = 30 and acct3 = 10
• P1 reads acct2 = 20
• P2 reads acct3 = 10
• P1 thinks acct1 = 10 (but it's really 30) and acct2 = 20
So P1 adds 10 to acct1 and subtracts 10 from acct2
Now acct1 = 40 and acct2 = 10
• P2 thinks acct2 = 20 (but it's really 10) and acct3 = 10
So P2 subtracts 10 from acct2 and adds 10 to acct3
Now acct2 = 0 and acct3 = 20

Final balances:

• acct1 = 40
• acct2 = 0
• acct3 = 20

However the sum of all three balances cannot change. This is because each exchange adds and removes an equal amount between accounts. So total deposits will always equal total withdrawals.