Maksim Dmitriev
Maksim Dmitriev

Reputation: 6209

compareAndSet in an if statement. Is it an atomic operation?

It's clear that compareAndSet is an atomic operation. But what about the two following code snippets?

if (value.compareAndSet(true, false)) // No negation

or like this:

if (!value.compareAndSet(true, false)) // There is a negation

I think the first operation is atomic (but not quite sure because there is an if), and the second one is definitely not atomic because it consists of compareAndSet and a negation.

Upvotes: 0

Views: 1283

Answers (1)

Thilo
Thilo

Reputation: 262494

This code more or less compiles to

boolean result = value.compareAndSet(true, false)
if (result){
// or
if (!result){

That result is a local variable (and moreover a primitive).

There is no way that other threads can get to it and someone "corrupt it".

Of course, the AtomicBoolean itself may have a different value the next time you look at it. But you will still know if your compareAndSet was successful.

Upvotes: 1

Related Questions