user1028741
user1028741

Reputation: 2815

How can I use CAS (Compare-and-swap) in java?

I've read about the possibility to use CAS instruction of the processor, using Java.

As I googled for an examples, I only found classes such as SimulatedCAS. This class is obviously only a simulation of CAS (as its name implies...), using commmon "synchronized" on it's class methods.

So I wonder, how can one really use the CAS instruction using Java?

Upvotes: 2

Views: 626

Answers (1)

David Ehrmann
David Ehrmann

Reputation: 7576

Look into classes like AtomicBoolean and AtomicReference. They're abstractions that do what you want, but aren't actually on the CPU.

One pattern I've used is for thread-safe state keeping.

private final AtomicBoolean isClosed = new AtomicBoolean(false);

...

public void close() {
    if (this.isClosed.compareAndSet(false, true) {
        ....
    }
}

Upvotes: 3

Related Questions