OlliP
OlliP

Reputation: 1585

"Ternary CAS operation" theoretically possible?

I often encounter situations where I wished the problem could be solved somewhat like this:

AtomicBoolean bool1 = new AtomicBoolean();
AtomicBoolean bool2 = new AtomicBoolean();

boolean expected = false; // whatever
boolean update = false; // whatever

if(bool1.get()) {
    bool2.compareSet(expected, update);
}

But this does not work as there can be context switches between bool1.get() and bool2.compareSet(...). So what is needed is something I would call a "ternary atomic boolean", which is something that can do bool1.get() and bool2.compareSet(...) in one CAS operation.

My question is whether it can be done. Does anyone know of someone thinking about this problem as well (some university) or does anyone know of an existing solution that comes close to what is needed (I mean without locks, synchronized blocks, mutexes, semapores, but with the use of a CAS-based algorithm only).

Upvotes: 1

Views: 58

Answers (1)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

Use AtomicInteger, which also has a CompareSet method, and model your booleans as bitfields. You can model 32 booleans in one integer.

Upvotes: 5

Related Questions