What is AtomicLong in Java used for?
Asked Answered
P

1

54

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;
Peregrination answered 22/2, 2016 at 6:18 Comment(0)
O
65

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 need the wrapper class
  • You are working with a collection
  • You only want to deal with objects and not primitives (which kinda works out)

You use an AtomicLong when:

  • You have to guarantee that the value can be used in a concurrent environment
  • You don't need the wrapper class (as this class will not autobox)

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.

Overdraw answered 22/2, 2016 at 6:59 Comment(2)
When you write : "Long by itself doesn't allow for thread interopability since two threads could both see and update the same value" , how is it possible to modify a Long object ? I thought that Longs are immutable and I didn't found any method in the Long class to modify the value.Haematothermal
@PhilippeG.: Oh, you can always mutate a field if you don't properly synchronize it. The Long class is immutable but its place in memory isn't.Overdraw

© 2022 - 2024 — McMap. All rights reserved.