Is Java ArrayList / String / atomic variable reading thread safe?

前端 未结 6 1928
南方客
南方客 2021-02-14 00:27

I\'ve been mulling this over & reading but can find an absolute authoritative answer.

I have several deep data structures made up of objects containing ArrayLists, S

6条回答
  •  梦谈多话
    2021-02-14 00:57

    The members of an ArrayList aren't protected by any memory barriers, so there is no guarantee that changes to them are visible between threads. This applies even when the only "change" that is ever made to the list is its construction.

    Any data that is shared between thread needs a "memory barrier" to ensure its visibility. There are several ways to accomplish this.

    First, any member that is declared final and initialized in a constructor is visible to any thread after the constructor completes.

    Changes to any member that is declared volatile are visible to all threads. In effect, the write is "flushed" from any cache to main memory, where it can be seen by any thread that accesses main memory.

    Now it gets a bit trickier. Any writes made by a thread before that thread writes to a volatile variable are also flushed. Likewise, when a thread reads a volatile variable, its cache is cleared, and subsequent reads may repopulate it from main memory.

    Finally, a synchronized block is like a volatile read and write, with the added quality of atomicity. When the monitor is acquired, the thread's read cache is cleared. When the monitor is released, all writes are flushed to main memory.

    One way to make this work is to have the thread that is populating your shared data structure assign the result to a volatile variable (or an AtomicReference, or other suitable java.util.concurrent object). When other threads access that variable, not only are they guaranteed to get the most recent value for that variable, but also any changes made to the data structure by the thread before it assigned the value to the variable.

提交回复
热议问题