• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Atomic Integer Vs increment

 
kri shan
Ranch Hand
Posts: 1478
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which give better performnace for counter(how many hits for my site), Atomic Integer or increment (++)
 
Henry Wong
author
Marshal
Pie
Posts: 21515
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kri shan wrote:Which give better performnace for counter(how many hits for my site), Atomic Integer or increment (++)


First, you do know that one is thread safe and the other isn't right? Under single threaded conditions, it's kinda not a fair comparison. And under multithreaded conditions, well, one isn't guaranteed to work correctly.

Henry
 
Pablo Abbate
Ranch Hand
Posts: 30
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kri shan wrote:Which give better performance for counter(how many hits for my site), Atomic Integer or increment (++)


If you have multithreads, use AtomicInteger, if not, use the common increment.
 
Tony Docherty
Bartender
Posts: 2990
59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kri shan wrote:Which give better performance for counter

What do you mean by better performance, is it accuracy, speed or something else altogether?

Pablo Abbate wrote:If you have multithreads, use AtomicInteger, if not, use the common increment.

I think the decision is a bit more complex than that.
It may be that the reads and writes are currently done from within synchronized blocks for other reasons we are not aware of or it maybe that the hit counter is only indicative and so (providing writes are done from within a synchronized block) occasionally being out by a few hits on reads may not be an issue.
 
Pablo Abbate
Ranch Hand
Posts: 30
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tony Docherty wrote:
kri shan wrote:Which give better performance for counter

What do you mean by better performance, is it accuracy, speed or something else altogether?

Pablo Abbate wrote:If you have multithreads, use AtomicInteger, if not, use the common increment.

I think the decision is a bit more complex than that.
It may be that the reads and writes are currently done from within synchronized blocks for other reasons we are not aware of or it maybe that the hit counter is only indicative and so (providing writes are done from within a synchronized block) occasionally being out by a few hits on reads may not be an issue.


I mean if the counter is being (or can be) updated with multiple threads.
If the counter is inside a synchronized block, you don't have multithreads accessing the counter.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic