I recently encountered atomic classes from java.util.concurrent.atomic package. As far as I know, immutable classes are by default thread safe by nature, so we do not need to synchronize them. Later I came to know that wrapper classes like Integer, Boolean, Character, etc are immutable by nature, so why do we need Atomic* classes like AtomicInteger or AtomicLong. Also, please explain what is AtomicReference.
The atomic classes are mutable, but have strong memory consistency guarantees with regard to modifications. So they serve a different purpose from the immutable wrapper classes.
The real advantage of the Atomic* classes is that they expose an atomic compare-and-swap method, which can be very useful for implementing lock-free algorithms.
Like many intermediate to advanced concurrency tools, if you can't imagine why you would need such a thing then you probably shouldn't try to use them. If you stick to immutability or explicit locking everywhere then you probably won't need atomics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With