aknon
aknon

Reputation: 1458

Java concurrency primitive - compare and swap

Java 5, introduced few concurrency primitive like compare and swap, compare and set ( together clubbed as CAS ) and some others.
All these operations, as I know, have been guaranteed to be atomic. It seems that for each of these operation, hence, there must be a single JVM byte code instruction ?

I was going through the list of byte code instructions, but did not find any for methods like CAS.

Not sure, I am correct in saying that CAS must have a single byte code instruction, or is there a different way CAS institutions are executed/implemented in java ?

Upvotes: 2

Views: 2817

Answers (2)

Andrey Chaschev
Andrey Chaschev

Reputation: 16486

From Java CAS operation looks like a native method call to an object of class sun.misc.Unsafe. An example from the AtomicInteger:

/**
 * Atomically sets the value to the given updated value
 * if the current value {@code ==} the expected value.
 *
 * @param expect the expected value
 * @param update the new value
 * @return true if successful. False return indicates that
 * the actual value was not equal to the expected value.
 */
public final boolean compareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

More on Unsafe: https://stackoverflow.com/questions/5574241/interesting-uses-of-sun-misc-unsafe.

Upvotes: 2

Stephen C
Stephen C

Reputation: 718826

It seems that for each of these operation, hence, there must be a single JVM byte code instruction ?

In fact, these operations are implemented as native code methods which use hardware-specific instructions or instruction sequences to achieve the required semantics. There are no JVM bytecodes for doing CAS operations.

Upvotes: 5

Related Questions