Atomic classes
Data integrity can easily be a problem in a concurrent program. Imagine two threads reading a value, and then both changing it and overwriting each other’s change right after. This could, for example, result in a counter that ends up being only one higher, while it should be two higher. Data integrity gets lost! This is where atomic classes come in.
Atomic classes are used for atomic operations. That means that the read (getting a value) and write (changing a value) are considered one operation instead of two separate ones. This avoids the problems with data integrity that we just demonstrated. We’ll briefly discuss how to use AtomicInteger
, AtomicLong
, and AtomicReference
.
AtomicInteger, AtomicLong, and AtomicReference
There are several atomic classes for basic data types. We have AtomicInteger
to represent an integer value and support atomic operations on it. Similarly, we have AtomicLong
for the Long
type. We have AtomicReference
for references...