Explain optimistic and pessimistic locking.
sobes.tech AI
Answer from AI
Optimistic and pessimistic locking are two approaches to managing concurrent access to data.
-
Pessimistic locking assumes conflicts will occur, so it locks the resource in advance (for example, using a mutex) to prevent others from modifying it while the current process is working. This prevents race conditions but can reduce performance due to waiting.
-
Optimistic locking assumes conflicts are rare. The process reads data without locking, and when writing, it checks whether the data has changed since it was read (for example, using a version or timestamp). If the data has changed, the operation is rolled back or retried.
In Go, pessimistic locks are implemented using sync.Mutex or sync.RWMutex. Optimistic locks require additional logic, such as atomic operations or version comparisons.
Example of pessimistic locking:
var mu sync.Mutex
mu.Lock()
// critical section
mu.Unlock()
Optimistic locking might look like this (simplified):
version := atomic.LoadInt64(&dataVersion)
// read data
// attempt to write
if !atomic.CompareAndSwapInt64(&dataVersion, version, version+1) {
// data changed, retry
}