0

I have been reading about SMPs machines(x86/ARM)and Compiler reordering for efficiency. Now I want to make a counter and the variable lives as a private member of ActivityLifecycleCallbacks implementation. The operations on this variable is performed on the callbacks from Android(which in always on UI thread).

Now because "x++" is not an atomic statement. Do I need to use AtomicInteger ? even If the variable is always only accessed on UI Thread?

Jai Pandit
  • 510
  • 1
  • 6
  • 18

1 Answers1

-1

If it's only ever accessed by the UI thread, then technically, no you wouldn't need to use an AtomicInteger. When I say access, I mean for both reads and writes.

However, considering you are working under a concurrent architecture, it's probably safer just to use a concurrent object like AtomicInteger or the more performant LongAdder.

John Vint
  • 39,695
  • 7
  • 78
  • 108
  • not sure what do you mean by "Safer". I'd like to have a solid concrete and confident understanding about it. I do not want myself to feel unsafe doing the right thing! – Jai Pandit Dec 04 '19 at 18:06
  • My first comment is the answer, if the UI thread is the only one ever touching the field then you don't need an AtomicInteger. – John Vint Dec 04 '19 at 18:22
  • Thats my understanding as well, However I'd like to point out here that its not just me dealing with SMPs. Most of the newer Android devices are based off SMP architecture being it x86 or ARM. So most of Android Developers are actually on SMPs only or their apps are running on them only. – Jai Pandit Dec 04 '19 at 18:26