Add swap-vals! and reset-vals! (swap! and reset! that return [old new])

Description

Sometimes, when swapping or resetting an atom, it's desirable to know the value before the update. The existing swap! and reset! functions return the new value instead. Currently, the only option is to roll your own using a loop and compare-and-set!

Example use cases:

  • When an atom contains a PersistentQueue and you want to atomically remove the head of the queue and process it: if you run (swap! q pop), you have lost the reference to the old head of the list so you can't process it.

  • Want to check if an operation has occurred before by using atom as a flag (this can be achieved with compare-and-set! but reads a little easier this way).

  • Want to use an atom similarly to a java.util.concurrent.LinkedTransferQueue, for the case of pairing up adds by writers and drainTo y readers:

Approach: Add clojure.core/swap-vals! and clojure.core/reset-vals! that return [old new]

Patch: clj-1454-4.patch

Environment

None

Activity

Show:
Alex Miller
May 12, 2017, 9:34 PM

Rich has ok'ed looking at this for 1.9 but did not like the name.

Stuart Halloway
May 13, 2017, 3:46 AM
Leon Grapenthin
May 13, 2017, 1:21 PM

Doesn't seem ideal to me. Get already has a different meaning in Clojure.
An idea:
before-swap!

Alex Miller
May 13, 2017, 2:41 PM

Please, let's not bikeshed the name any more on here. Stu and I will figure out something with Rich.

Rich Hickey
August 30, 2017, 7:18 PM

If we are going to add something here it should return both before/after, else there will still be no way to get both

Completed

Assignee

Unassigned

Reporter

Philip Potter

Labels

Approval

Ok

Patch

Code and Test

Fix versions

Priority

Critical
Configure