AtomicBoolean vs Synchronized block, whats the difference

旧城冷巷雨未停 提交于 2019-11-29 14:15:28

There are a few subtle differences but seen from the outside the two code snippets behave similarly: if you call the set method, the change will be visible to other threads calling get subsequently.

The main differences are:

  • performance: depending on the level of contention, you may get better performance with synchronized or AtomicBoolean
  • atomicity: if at some stage you want to do more than just setting the boolean value, a synchronized block will allow you to add instructions atomically but AtomicBoolean won't

If all you're trying to do is make getting and setting a single boolean value atomic, then yes - you can use AtomicBoolean instead without any synchronization.

Of course, synchronized allows a far wider range of uses, such as performing several actions within the block without losing the lock, or using it for wait/notify. So it's not like AtomicBoolean is a general alternative to synchronization - but in this case you can use it instead of synchronization.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!