Microbenchmarks: Java Locks vs. Atomic
blog.tombert.com
blog.tombert.com
Why is it faster than synchronized? This is probably because (depending on your jvm) ReentrantLock is built on LockSupport.park, which is virtual thread aware, and synchronized is operating directly on the platform threads.
That's interesting, I'll rewrite the tests with vanilla threads and update the page!
ETA:
Ok, I updated the tests to use vanilla platform threads, and surprisingly ReentrantLock is still faster. Here are the results:
Total time for synchronized: 202ms, counter: 2000000
Total time for atomic: 27ms, counter: 2000000
Total time for lock: 58ms, counter: 2000000This type of benchmark is a pathological because the optimal scheduling policy is for one thread to starve all the others until it finishes, which is basically never what you'd want in a real project.
People have pointed out that I should probably be using something like JMH instead of basic timers. I plan on writing an update to this with those numbers.
The numbers are bad because OP is using manual benchmarking and falling for the microbenchmarking traps with JIT optimizations. There's no warmup or anything...