Synchronizing an object shared across threads, but not accessed concurrently

后端 未结 5 1534
我寻月下人不归
我寻月下人不归 2021-01-16 19:23

Let\'s say I have a shared object with field data. Multiple threads will share a reference to this object in order to access the field. The threads never access

5条回答
  •  北海茫月
    2021-01-16 19:46

    Mutations from a thread are guaranteed to become visible to other threads only when an happen-before relationship between the threads is established. When the relationship is established, all previous mutations become visible.

    An object that isn't correctly synchronized when taken in isolation can be safe to use if another object correctly synchronizes accesses to it (see piggibacking in Java Concurrency in Practice).

    In the two cases described in the question, I think no synchronization is needed:

    • Thread.start establishes a happen-before relationship, so all mutations from previous threads are visible
    • Accesses to object X are synchronized by object Y, which will establish happen-before relationships and make the changes to X visible (I expanded a bit more in a blog post).

    If you know that an object X is never accessed concurrently, chances are there is an object Y that indirectly synchronizes accesses to X, so it's fine. The only unsafe case I see is if threads relay on time itself (e.g. with Thread.sleep or by looping until some time has elasped) to guarantee mutual exclusion: in this case there is no happen-before relationship that is established.

提交回复
热议问题