Is there any justification not to ALWAYS use AtomicInteger as data members?

早过忘川 提交于 2019-12-22 10:13:05

问题


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?


回答1:


Is there any justification not to ALWAYS use AtomicInteger as data members?

Yes, there are good reasons to not always use AtomicInteger. AtomicInteger can be at at least an order of magnitude slower (probably more) because of the volatile construct than a local int and the other Unsafe constructs being used to set/get the underlying int value. volatile means that you cross a memory barrier every time you access an AtomicInteger which causes a cache memory flush on the processor in question.

Also, just because you have made all of your fields to be AtomicInteger does not protect you against race conditions when multiple fields are being accessed. There is just no substitute for making good decisions about when to use volatile, synchronized, and the Atomic* 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:

synchronized (someObject) {
   someObject.count++;
   someObject.total += someObject.count;
}

If both of those members with AtomicInteger then you'd be accessing volatile twice so crossing 2 memory barriers instead of just 1. Also, the assignments are faster than the Unsafe operations inside of AtomicInteger. Also, because of the data race conditions with the two operations (as opposed to the synchronized blocks above) you might not get the right values for total.

Can you bring an example of thread-safe int data member usage?

Aside from making it final, there is no mechanism for a thread-safe int data member except for marking it volatile or using AtomicInteger. 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 your synchronized blocks. To find the right fields that should be marked with volatile. To find the proper places to use AtomicInteger and friends.




回答2:


If you have effecitvely immutable ints you can get away with not ensuring synchronization at the cost of its calculation. An example is hashCode

int hash = 0;

public int hashCode(){
   if(hash == 0){
     hash = calculateHashCode(); //needs to always be the same for each Object
   }
   return hash;
}

The obvious tradeoff here is the possibility of multiple calculations for the same hash value, but if the alternative is a synchronized hashCode that can have far worse implications.

This is technically thread-safe though redundant.




回答3:


It depends on how it is used wrt. other data. A class encapsulates a behavior, so often a variable is almost meaningless without the others. In such cases it might be better to protect(*) data members that belong together (or the whole object), instead of just one integer. If you do this, then AtomicInteger is an unnecessary performance hit

(*) using the common thread safety mechanisms: mutex, semaphore, monitor etc.




回答4:


Thread safety is not only about atomic int assignments, you need to carefully design your locking patterns to get consistency in your code.

If you have two Account classes with a public datamembers Balance consider the following simple code.

Account a;
...
int withdrawal = 100;
if(a.Balance >= withdrawal)
{
    // No atomic operations in the world can save you from another thread
    // withdrawing some balance here
    a.Balance -= withdrawal
}
else
{
   // Handle error
}

To be really frank. In real life, having atomic assignments is rarely enough to solve my real life concurrency issues.



来源:https://stackoverflow.com/questions/11125449/is-there-any-justification-not-to-always-use-atomicinteger-as-data-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!