ArrayList concurrent access

后端 未结 3 829
野趣味
野趣味 2021-01-14 05:56

I am aware that ArrayList is not thread safe, but I\'m unsure about the exact implications of this.

In the case of ThreadA and Thread

3条回答
  •  无人及你
    2021-01-14 06:25

    In your question I see an emphasis on simultaneous access.

    The issues with concurrent access have very little to do with simultaneity. To put it more strongly, even if you ensure no simultaneous access happens, you are still a long way from a thread-safe program.

    Answers to your specific points:

    1) Both threads simultaneously reading the same index

    As long as your threads only read and never write, you are safe regardless of simultaneity.

    2) ThreadA changing an element which ThreadB is attempting to access simultaneously, assuming that you don't care whether or not ThreadB gets the old or the new element.

    Whether or not writing happens at the same time as reading, you are in trouble. You are not just in danger of seeing stale values; you can see a completely broken List object (its internal state is inconsistent).

    If any thread changes the list, you need synchronization.

    For more information I strongly advise getting acquainted with the Java Memory Model, preferrably from the corresponding section in the Java Language Specification.

提交回复
热议问题