Long primitive or AtomicLong for a counter?

Posted by Rich on Stack Overflow See other posts from Stack Overflow or by Rich
Published on 2010-03-15T14:57:52Z Indexed on 2010/03/15 14:59 UTC
Read the original article Hit count: 197

Hi

I have a need for a counter of type long with the following requirements/facts:

  • Incrementing the counter should take as little time as possible.
  • The counter will only be written to by one thread.
  • Reading from the counter will be done in another thread.
  • The counter will be incremented regularly (as much as a few thousand times per second), but will only be read once every five seconds.
  • Precise accuracy isn't essential, only a rough idea of the size of the counter is good enough.
  • The counter is never cleared, decremented.

Based upon these requirements, how would you choose to implement your counter? As a simple long, as a volatile long or using an AtomicLong? Why?

At the moment I have a volatile long but was wondering whether another approach would be better. I am also incrementing my long by doing ++counter as opposed to counter++. Is this really any more efficient (as I have been led to believe elsewhere) because there is no assignment being done?

Thanks in advance

Rich

© Stack Overflow or respective owner

Related posts about java

Related posts about java.util.concurrent