Skip to content

Contention

Category: Hazards · Status: stub · Lessons: chapter 02, Shared state

One line: Tasks competing for the same lock or resource, so their time goes to waiting instead of working — the reason adding threads can make a program slower.

Also called: lock contention.

How it connects

flowchart LR
  n_contention["Contention"]
  n_mutex["Mutex"]
  n_oversubscription["Oversubscription"]
  n_mutex -->|can cause| n_contention
  n_oversubscription -->|can cause| n_contention
  classDef center stroke-width:3px
  class n_contention center
  classDef outside stroke-dasharray: 4 3
  class n_mutex,n_oversubscription outside

In each language

Go runtime.SetMutexProfileFraction turns on the mutex profile ↗ of contended mutexes; the block profile shows where goroutines wait
Java ThreadMXBean thread contention monitoring accumulates the time each thread has blocked for synchronization
Python functools.cached_property dropped its lock in 3.12 because the lock was per property, not per instance, and caused high lock contention
C# Monitor.LockContentionCount counts the times taking a monitor's lock met contention

Where to read more