Search code examples
javaatomicsynchronized

Is there a viable use case where Java synchronized keyword is better than Atomics?


I've not much experience with threading, but I wrote a nifty non-blocking sequential Id generator with Atomics.... It got me a very significant performance boost in testing. Now I wonder why anyone would use synchronized since it is so much slower... is there a reason on modern 64 bit multi-core hardware? Others are asking me about Atomics now. I would love to be able to tell them to never use that keyword unless they are deploying to ancient hardware.


Solution

  • Because you can't do multiple actions exclusively using only atomics (well, technically you can, because you can implement a "lock" using atomics, but i think that's beside the point). you also can't do a blocking wait using atomics (you can do a busy wait, but that's almost always a bad idea).

    here's an exercise for the OP: write a program which writes timestamped log messages using multiple threads to the same file where the messages must show up in the file in timestamp order. implement this using only atomics, but without re-inventing ReentrantLock/synchronized.