Can some one explain what AtomicLong is used for? For example, what's the difference in the below statements?
private Long transactionId; private AtomicLong transactionId;
If you want to create an AtomicLong with an initial value, you can do so like this: AtomicLong atomicLong = new AtomicLong(123); This example passes a value of 123 as parameter to the AtomicLong contructor, which sets the initial value of the AtomicLong instance to 123 .
Yes it is. And AtomicLong is too. Not only is it thread-safe, but in fact its thread-safety is the only reason to use it (as opposed to a plain int ).
Java provides atomic classes such as AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Objects of these classes represent the atomic variable of int, long, boolean, and object reference respectively. These classes contain the following methods.
There are significant differences between these two objects, although the net result is the same, they are definitely very different and used under very different circumstances.
You use a basic Long
object when:
You use an AtomicLong
when:
Long
by itself doesn't allow for thread interopability since two threads could both see and update the same value, but with an AtomicLong
, there are pretty decent guarantees around the value that multiple threads will see.
Effectively, unless you ever bother working with threads, you won't need to use AtomicLong
.
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