1

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 ?

aknon
  • 1,408
  • 3
  • 18
  • 29

2 Answers2

5

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • It brings me to another question ( perhaps I should have added this to the title question) - Why did java ignore this CAS operation for concurrency, until java 1.5 , whereas cas instructions were supported by processors since early times, around 1970. – aknon Dec 26 '13 at 12:17
  • @aknon - That's not a question we can answer. – Stephen C Jun 30 '15 at 02:47
2

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.

Community
  • 1
  • 1
Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68