In Java, is it required to synchronize write access to an array if each thread writes to a separate cell space?

前端 未结 10 1759
北恋
北恋 2020-12-15 17:14

Is it required to synchronize write access to an array in Java if each thread writes to a separate cell space?

EDIT: Specifically, the array is eith

10条回答
  •  北海茫月
    2020-12-15 17:28

    Are the same threads also reading the value. If so then you are ok. If not then you need to worry about whether other threads see the most recent values. This is usually taken care of through the key work volatile or through atomics variables.

    For example if you have an int [] intArray with three elements.
    
    thread 1 updates intArray[0]=
    thread 2 updates intArray[1]=
    thread 3 updates intArray[2]=
    

    if these threads also are used to read the values then you are ok but if a new thread --> thread 4 attempts to read the values then there is no guarantee that it will see the latest assignment.

    you'll be ok if you use AtomicIntegerArray, AtomicLongArray, or AtomicReferenceArray

提交回复
热议问题