As it has been already mentioned, you can not simply swap value using neither volatile boolean nor AtomicBoolean in one line.
There are two ways you can do it, which also showed above:
- using one "global" lock/synchronization
- via while loop and AtomicBoolean.compareAndSet
Whereas the first solution looks easier and just works, in my opinion, in most cases it would be considered as a bad practise and should be avoided. Unless you have a really high count of simultanious modifications of this field by multiple threads, the second solution should outperform the first one.
Nevertheless, if you really favor simplicity and do not need a better performance knowing the cost of this decision, choose the first.
To add my contribution, I have noticed that you defined your atomic variable as volatile
, and, just in case, warn you, that if you do not reassign this field and it can be made final
, better do it final
. volatile
applies only to the actual field value and if you do not change it (which you do not using set/compareAndSet
methods of AtomicBoolean
) and you have made sure, that other threads will see the initialized value (final
does it) there is no much sense to use it.