I Benchmarked CAS vs. a Lock — and Caught Myself Drawing the Wrong Conclusion Halfway Through

java dev.to

"Lock-free beats locks" is close to something of a folk wisdom in Java concurrency circles. Wanting a concrete answer, I implemented both a hand-rolled compare-and-swap (CAS) retry loop and a plain synchronized counter in a Java project — benchmarked the two against each other under JMH with a 1/2/4/6/8 thread sweep on 4-core hardware. The first result I'd gotten almost led me to a precisely the sort of over generalization that made me want to run the test in the first place. The setup

Read Full Tutorial open_in_new
arrow_back Back to Tutorials