Saturday, 23 April 2016

What is the difficulty with atomicity using multiple state varibles ?


Example
public class Test {
   private final AtomicReference<BigInteger> values 
        = new AtomicReference<BigInteger>();
   private final AtomicReference<BigInteger[]> factors
        = new AtomicReference<BigInteger[]>();

   public void process(BigInteger in) {
      // ------
   }
}

Problem
Using atomic references, we cannot update both values and factors simultaneously.
Similarly, both values cannot be fetched simultaneously.

Between the time when thread A fetches the two values, thread B could have changed them.

Solution
Update related state variables in single atomic operation instead of 2 different atomic variables.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.