javabooleanatomicboolean

Get the updated value first in AtomicBoolean


getAndSet returns the "previous" value then set the updated value, I want the "reverse" behavior, to return the updated value and then set it in the AtomicBoolean object. just like when you do

if(bolVal = otherBolVal)

the assignment here precedes the evaluation. can it be done with AtomicBoolean alone or do I need a custom class which is not good for me.

I had this

sharedPref.edit().putBoolean("tag", isOvertime = false).apply();

which was done in one line, now I was forced to pass the boolean as a mutable object so I didn't want to create a custom class and went for AtomicBoolean. now I'm looking for a way to do the same one line assignment with least efforts without creating a new class or an extra line expression.


Solution

  • Something like this?

    private final AtomicBoolean atomicBoolean = new AtomicBoolean();
    
    public boolean setAndGet(boolean bool) {
        atomicBoolean.getAndSet(bool);
        return bool;
    }
    

    Nope you will need a custom class that extends AtomicBoolean or a Utils class. There is no reason to have a method for this in AtomicBoolean. Even in your case it's just one more line of code...