1

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
Manas Saxena
  • 2,171
  • 6
  • 39
  • 58
  • If you don't actually care about reading the right value, why do you care about storing the value at all? – Andy Turner Jul 12 '21 at 17:48
  • The value is the current timestamp which is updated by 5000 threads concurrently(within a second), I only require it to be approximately accurate to 1 minute. Hence am tolerant to reads returning value about less than a minute older – Manas Saxena Jul 12 '21 at 17:53
  • 2
    5K threads. I smell a serious design problem. – pveentjer Jul 12 '21 at 18:25
  • This is a spring boot server, the server can receive 5k http request per second. In each http request I need to update the variable. Agreed each http request might not translate to a new jvm thread – Manas Saxena Jul 12 '21 at 18:28
  • Probably an atomic long is more than good enough in your case. Probably some atomic read modify write behaviour is needed. – pveentjer Jul 12 '21 at 18:35

1 Answers1

-1

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

Vishal
  • 674
  • 1
  • 7
  • 20
  • Why is that better than `volatile`? – VGR Jul 12 '21 at 21:12
  • @VGR Using ```volatile``` what we can achieve is communication effects of ```synchronization```; not ```atomicity```. To perform atomic operation, we need to guard write access to ```volatile``` member with ```synchronization```. On the other hand, you can use ```AtomicLong``` without an additional explicit guard with ```synchronization``` For better understanding, read ```Item 78``` from ```Effective Java - Joshua Bloch``` – Vishal Jul 13 '21 at 06:19