is there any advantage of using AtomicLong if you are only setting and getting the value?

1.9k views Asked by At

I have a need for a long instance variable.
This variable will hold some event time (time in milliseconds).
If i'm only setting values into this long and getting the value,
is there any advantage of using AtomicLong (and only its get() and set()) rather than long?

4

There are 4 answers

1
dtortola On

If you are not using its value in its own updates, you don't need it, but if you intend to do something like var.set(1+var.get()) and you use several threads there's, among others, this possibility:

Thread 1: x=var.get(); x=x+1;

Thread 2: y=var.get(); y=y+1;

Thread 1: var.set(x);

Thread 2: var.set(y);

With that sequence, the user expects the value to have been increased by 2, but they'll see it's been increased only by 1

1
Suresh Atta On

Look at the doc of AtomicLong

An AtomicLong is used in applications such as atomically incremented sequence numbers, and cannot be used as a replacement for a Long.

This specific class is designed to use in multi threaded environment for thread safety.

Do not use it unless you need thread safety. You can provide your own getter and setters for your long variable, if you want only those methods.

5
OldCurmudgeon On

Yes there are advantages.

  1. In a multithreaded environment you will get predictable results between threads.
  2. It is a convenient mutable long.

However, if you are not operationg in a multithreaded environment and all you want is a mutable long you would be better to use your own mutable object. Using AtomicLong in this case would be confusing for others and will perform unnecessary cache management.

0
inor On

There is no advantage as long as the primitive long is declared volatile, or if a 64 bit JVM is used. An assignment to a simple (non-volatile) long in a 32 bit JVM is not atomic, so one thread can start the assignment (some bytes moved into the long, but not all) and then another thread can read/access the long and get a corrupt value. In a 64 bit JVM the assignment and access are atomic. Similarly if you declare the long as volatile, it will be assigned/accessed atomically.