In a multi-threaded environment like Android, where a simple int variable may be manipulated by multiple threads, are there circumstances in which it is still justified to use an int as a data member?
An int as a local variable, limited to the scope of the method that has exclusive access to it (and thus start & finish of modifying it is always in the same thread), makes perfect sense performance-wise.
But as a data member, even if wrapped by an accessor, it can run into the well known concurrent interleaved modification problem.
So it looks like to “play it safe” one could just use AtomicInteger across the board. But this seems awfully inefficient.
Can you bring an example of thread-safe int data member usage?
Yes, there are good reasons to not always use
AtomicInteger.AtomicIntegercan be at at least an order of magnitude slower (probably more) because of thevolatileconstruct than a localintand the otherUnsafeconstructs being used to set/get the underlyingintvalue.volatilemeans that you cross a memory barrier every time you access anAtomicIntegerwhich causes a cache memory flush on the processor in question.Also, just because you have made all of your fields to be
AtomicIntegerdoes not protect you against race conditions when multiple fields are being accessed. There is just no substitute for making good decisions about when to usevolatile,synchronized, and theAtomic*classes.For example, if you had two fields in a class that you wanted to access in a reliable manner in a thread program, then you’d do something like:
If both of those members with
AtomicIntegerthen you’d be accessingvolatiletwice so crossing 2 memory barriers instead of just 1. Also, the assignments are faster than theUnsafeoperations inside ofAtomicInteger. Also, because of the data race conditions with the two operations (as opposed to thesynchronizedblocks above) you might not get the right values fortotal.Aside from making it
final, there is no mechanism for a thread-safeintdata member except for marking itvolatileor usingAtomicInteger. There is no magic way to paint thread-safety on all of your fields. If there was then thread programming would be easy. The challenge is to find the right places to put yoursynchronizedblocks. To find the right fields that should be marked withvolatile. To find the proper places to useAtomicIntegerand friends.