Long primitive or AtomicLong for a counter?
- by Rich
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