Search code examples
javamultithreadingthread-safetyatomic

How to check another condition before set AtomicBoolean?


I have an AtomicBoolean and want to set it, if another condition is also true:

For example we have a bankaccount with an Active and Saldo field. In the method setInctive, I have to check if the Saldo field is exactly zero and then set the Active field to false.

This is my solution, but I'm not sure if this really works!

private final AtomicBoolean active = new AtomicBoolean(true);
private final AtomicReference<Double> saldo = new AtomicReference<>(0.0);

@Override
public boolean setInctive() {
    //First: check if saldo is 0.0
    //Second: set active to false

    saldo.getAndUpdate(aDouble ->  {
        if(aDouble == 0)
            active.set(false);

        return aDouble;
    });

    //return negated value of the active field
    return !active.get();
}

What would be a correct solution with atomics and is this even possible without using locks?


Solution

  • One possible way to and check another condition and set a boolean, is to use an AtomicMarkableReference. Im my example of type Double:

    private final AtomicMarkableReference<Double> saldo = new AtomicMarkableReference<>(0.0, true);
    
    @Override
    public boolean setInctive() {
        return saldo.attemptMark(0.0, false);
    }
    

    The saldo field now represents not only the current saldo, but also the status of the bank account.