Background
I'm using an open source off-heap cache implementation, ohc.
Recently, I found a pull request on github which suggests to
replace spin-on-compare-and-set with spin-on-read.
Here is the change of code, it adds only one line while(lockFieldUpdater.get(this) != 0L)
, which like
while (true)
{
if (lockFieldUpdater.compareAndSet(this, 0L, t))
return true;
// while(lockFieldUpdater.get(this) != 0L)
Thread.yield();
}
Benchmark performance
I compile it and use the benchmark tool to test it:
Online performance
Then I use it on production, the original average time cost of reading is about 35,000 nanoseconds, and it only cost 10,000 nanoseconds with the new version.
Question
What's the difference of these two implementations? Why test-on-read is much more faster in this case?