简体   繁体   中英

Is it atomic operation to read/write elements in a array?

I have multiple threads accessing the elements from one shared array marked as final (I'll never try to assign another array to it). Do I need to synchronize anything? Can I assume that the read/write to an element is atomic?

The writes are atomic unless the array is of type long or double. However, the atomic property won't help you because the writes won't be guaranteed to be visible to other threads.

If the array is of reference type, the problem is even worse because other threads may see your objects torn apart: some fields visible, some not.

To safely share a random-access collection of elements, you'll need either a synchronizedList wrapper around a plain ArrayList , or a lock-free CopyOnWriteArrayList .

If you are OK with the fixed size of an array (and it would seem so), then also look into AtomicReferenceArray since it allows atomic compare-and-set and get-and-set operations, which may take you a step further in implementing what you need without the need for locks.

since you have multiple threads that can read and write the elements of the vector, it can happen that when a thread reads, another writes the same cell. put a synchronized block. pseudo code example:

    public void get(index i){
        synchronized(..){
           //your code
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM