The simplified scenario is that I have an array of LongAdders and multiple threads are accessing this array in order to increment variable at a given index.
Is it safe to arraycopy without any additional locking mechanism?
As far as I've investigated into this matter it should be ok, because all significant fields of LongAdder are volatile and due to description increment() should be atomic (that is I hope it does not keep any partial state that may be of any problem in future operations).
Can anyone confirm this?
P.S. I am aware that I might not get the most recent snapshot (increments during the copying), but that is ok.
A LongAdder
array will only contain references anyway, so that's what will be copied. The fields within LongAdder
are irrelevant to that.
Whether it's "safe" to use arraycopy
depends on what you're doing with it - if you're using that to copy one array to another, then that's fine (in itself; you'd need to worry about how the array is made visible to threads though). If you're using it to copy one portion of an array to another portion of the same array, you should consider the possibility of multiple threads reading from the same index and getting different references.