Thread-safe negated AtomicBoolean get() as a condition in a while loop

Viewed 2395

Suppose I have the following code:

AtomicBoolean condition;
condition = new AtomicBoolean(false);
(...)
while(!condition.get()){
   // do some stuff
}

I know that condition.get() is atomic, but, is !condition.get() atomic as well?

I mean, could it happen that one Thread read the boolean value atomically and then it were interrupted before applying the ! operation, so that another Thread gets into the loop before? If that's the case, would it be better to use a function such as:

private synchronized boolean checkNegatedCondition(AtomicBoolean cond){
    return !cond.get();
}

(...)

while(checkNegatedCondition(condition)){
   // do some stuff
}

Thanks in advance.

3 Answers
Related