Is it possible to do an atomic snapshot without retry?

Skip to first unread message

Herbert Ghil

Nov 12, 2012, 6:51:37 PM11/12/12
Hello, I'm new to scala-stm.

I'm wondering if it's possible to make a snapshot of a set of refs.
I need to to make a decision on a list of values at a given timestamp, and I'd like to use stm for this. For what I understand, opening a transaction can give me this possibility, but the transaction would be retried if one of the values I view has changed. And sometimes I don't need to know about this change. Is it possible, or is it a wrong use of stm?


Nathan Bronson

Nov 12, 2012, 8:40:24 PM11/12/12
The STM should work well for this. If you want to avoid retry, there are two approaches:

1) perform the reads in a transaction, but then do the rest of the work outside:

  val (x, y, z) = atomic { implicit txn => (xRef(), yRef(), zRef()) }
  if (decision(x, y, z)) ...

In this form the atomic block might retry (invisibly) until it gets a consistent snapshot of the refs, but once you get to the decision part there will be no more rollback. If you have a TMap or TSet you can call clone() inside the atomic block and rely on their lazy copy-on-write behavior for efficiency.

2) Use Ref.getWith(f), which will only roll the transaction back if f(ref.get) changes, rather than just the ref itself. For example, if x changes from 1 to 2 concurrent with the following transaction, there will be no rollback:

  atomic { implicit txn =>
    if (x.getWith( _ >= 0)) ...

  Since _ >= 0 yields true for both values, the result of getWith has remained stable and the transaction can complete. At the moment there is not a convenient form for a multi-Ref version of this construct.


Herbert Ghil

Nov 13, 2012, 6:38:40 PM11/13/12
Thanks for the suggestions.
For the second solution, I have the impression it's only practical for a specific use case. I may be interested in the value of x (for example returning the max of 2 values at a given time).
The first solution seems to be the way to go for my usage, even if a bit restrictive, as it force to evaluate all the refs I "may" need before the decision code.
Reply all
Reply to author
0 new messages