liveBook · Manning

Swap

As explained in Data-Oriented Programming: Reduce software complexity

An atom operation that repeatedly computes and conditionally installs a new value derived from the current value.

When several threads update a shared counter, a lock is not the only option. swap accepts a function, computes a new value from the current one, and installs it only if that value has not changed. section 8.2

The operation proceeds by retrying contested updates:

  • Read the atom's current value. section 8.2
  • Compute the next value by calling the supplied function. section 8.2
  • Compare the value with the original snapshot and retry if another update intervened. section 8.2

Incrementing a shared counter

Initialize an atom with zero, then call counter.swap(function(x) { return x + 1; }) for each database access. Read the total with counter.get().

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains the API, retry behavior, and compare-and-set loop, with language-specific implementation references.
Examples
Uses a database-access counter and Java Atom syntax to demonstrate incrementing and reading shared state.
What it assumes
Assumes concurrent shared-state updates while defining get, set, and swap as the atom's basic operations.
What you can do after
Apply swap via an atom to update shared state with a retrying compare-and-set pattern.
How it connects
Connects atoms with get, set, compare-and-set, mutexes, and thread-safe counters.

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming: Reduce software complexity. The section links point to the parts of the book it draws on.