←Older revision | Revision as of 16:21, 6 June 2025 | ||
Line 69: | Line 69: | ||
This is the correct code which removes the [[deadlock]] danger and still keeps consistency. A kind of manually written [[TransactionalMemory]]. First of all atomically read the values needed for the computation. Then release the lock and call the unknown code. Then obtain the lock again, make sure nobody else modified the internal state and if so, modify the state of the object. If the state of the object has been modified meanwhile, repeat the computation with new values. | This is the correct code which removes the [[deadlock]] danger and still keeps consistency. A kind of manually written [[TransactionalMemory]]. First of all atomically read the values needed for the computation. Then release the lock and call the unknown code. Then obtain the lock again, make sure nobody else modified the internal state and if so, modify the state of the object. If the state of the object has been modified meanwhile, repeat the computation with new values. | ||
- | + | === Cleaner Code === | |
- | + | {{:TransactionDataStructureExample}} | |
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
- | + | ||
Avoiding [[deadlock]]s this way sort of trades the [[deadlock]]s for live-locks. There is no limit to the number of times the '''while''' cycle is executed. Under some bad setup, it might even run indefinitely. It helps, if there is some invariant that gets stabilized with every change of the ''data'' field. For example {{NB|org-openide-util-lookup|org/openide/util/lookup|AbstractLookup}} is using the same approach and with every update of the ''data'' field, the internal data structure moves towards optimum - as a result it is clear that after some number of loops, there will be no clash and the update succeeds. | Avoiding [[deadlock]]s this way sort of trades the [[deadlock]]s for live-locks. There is no limit to the number of times the '''while''' cycle is executed. Under some bad setup, it might even run indefinitely. It helps, if there is some invariant that gets stabilized with every change of the ''data'' field. For example {{NB|org-openide-util-lookup|org/openide/util/lookup|AbstractLookup}} is using the same approach and with every update of the ''data'' field, the internal data structure moves towards optimum - as a result it is clear that after some number of loops, there will be no clash and the update succeeds. |