Question

Java exposes the CAS operation through its atomic classes, e.g.

AtomicInteger.compareAndSet(expected,update)

When expected == update, are these calls a no-op or do they still have the memory consistency effects of a volatile read+write (as is the case when expected != update)?

Was it helpful?

Solution

I went through the native code and there does not appear to be any difference in relation to the values being equal. Specifically in this case since integer equivalence doesnt do so on the reference.

It will run through the same logic with same memory consistencies in the event expected != update

One note is that there will always be at least a volatile load on the field's location, so you at the very least will have a volatile read of the backing int field.

OTHER TIPS

AFAIK there is no check for expected == update and no change in behaviour. To do so could add cycles if the hardware didn't do it already, which I suspect it doesn't.

I wouldn't write code which depends on side effects of calling CAS in any case.

You could add the check yourself if you think it is likely of course.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top