Atomic assignment of long value in java

309 Views Asked by At

I have the use case to update epoch time of events in a long variable. This variable will have lots of concurrent reads and writes as well. Here are the requirements in detail:

  1. Very fast completion of reads and writes
  2. Reads may or may not return latest result but should not return corrupted result
  3. Writes are simple assignment to a new epoch value, no addition, subtraction or calculation is required

Which of the alternatives is a better option for my use case:

  1. primitive long with volatile keyword
  2. AtomicLong
  3. LongAccumulator with accumulatorFunction being (x,y) -> y
  4. Two different variables - one for only reading values and other a volatile variable just for writing value, the value of write variable one being copied to read variable in some interval
1

There are 1 best solutions below

2
On

Use AtomicLong as it helps to avoid additional overhead of explicit locking