Tl;Dr: does CMPXCHG assume it will fail or succeed?
I am on Java 8, and need an atomic boolean. I don't want to pay higher
memory cost, so I am using an AtomicIntegerFieldUpdater. Right now I
have some code that looks
queue.add(work);
if (running.compareAndSet(this, stopped, running)) {
executor.execute(queueHandler);
}
I was looking at optimizing this code and noticed that compareAndSet()
could be changed to a getAndSet() pretty easily. Looking at the hotspot
code there are three atomic instructions that are used: cmpxchg, xadd, and
xchg.
Here is my question: the 2nd and 3rd instructions know for sure they are
going to modify the value, so they can bring in the cacheline as modified.
But, cmpxchg could potentially bring the cacheline in as
shared/exclusive/owned and not invalidate all the other caches. If I have
special knowledge that I will likely fail to exchange values, then wouldn't
it make sense to call get() just before compareAndSet() ? I wouldn't have
to do this is cmpxchg automatically did that for me, but then how could it
guess whether it will win or lose?
--
You received this message because you are subscribed to the Google Groups
"mechanical-sympathy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.