views:

75

answers:

2

I have a number of atoms in my code where a common requirement is to update them to a new value, regardless of the current value.

I therefore find myself writing something like this:

(swap! atom-name (fn [_] (identity new-value)))

This works but seems pretty ugly and presumably incurs a performance penalty for constructing the anonymous closure.

Is there a better way?

+8  A: 

The reset! function should do this.

(reset! atom-name new-value)
Pat Wallace
awesome... exactly what I was looking for!
mikera
+1  A: 

You can use (compare-and-set atom old-value new-value).

But I find it strange you need to change them so much to uncorrelated values. Can't you use bindings or similar things.

Peter Tillemans
It's for managing a unit of shared concurrent state across threads so bindings wouldn't work. AFAICS atoms seem to be the standard way of doing this.....
mikera
True, but I am worried about the semantics of a global variable which changes often to a value which cannot be transformed from the previous value. With a binding, you make a snapshot of the "shared" state till the capturing scope is left again. If this is not acceptable then there must be time-bound dependencies between threads and and some kind of inter-thread communication through the atom. I have not come accross a use-case like this, I usualy only have things like config, aggregations, or sessions/caches in atoms.
Peter Tillemans
Example: timers in a simulation. Different threads may need to read the latest global timestamp, only one thread ever updates it. Update is independent of the previous value.
mikera
Got it. Food for thought... thanks.
Peter Tillemans