Optimistic concurrency control

Optimistic concurrency control is a technique used for concurrency.

  • It is used in databases and internally by concurrent data structure libraries
  • It assumes that actions will generally complete without contention, so proceeds to perform the update immediately, then checks afterwards if the action can be committed or must be rolled back
  • Avoiding the use of locks provides a performance boost, especially for .NET code where a lock could require an expensive entry into kernel mode
  • Care must be taken in use and implementation, as high load can lead to increased contention, which increases the load etc.

 

Wikipedia

Advertisements

ConcurrentDictionary.GetOrAdd() facts

In any combination of any number of threads running for any values with the same key:

  • It is guaranteed that only one item will be added
    • and this will be the only call to which true is returned.
  • It is not guaranteed that the delegate overload will only execute the delegate once
    • because the class uses optimistic concurrency control.
    • The implicit assumption is that it’s rare for multiple concurrent calls to occur in reality, so more efficient to compute anyway, then replace or throw away as appropriate.
    • If the delegate is expensive or has unwanted side effects, a Lazy<> can be used instead.

ConcurrentDictionary.GetOrAdd()