Detailed semantics of volatile regarding timeliness of visibility

前端 未结 5 1734
北恋
北恋 2020-12-01 01:07

Consider a volatile int sharedVar. We know that the JLS gives us the following guarantees:

  1. every action of a writing thread w precedi
5条回答
  •  失恋的感觉
    2020-12-01 01:48

    I think the volatile in Java is expressed in terms of "if you see A you will also see B".

    To be more explicit, Java promises that when you thread reads a volatile variable foo and sees value A, you have some guarantees as to what you will see when you read other variables later on the same thread. If the same thread that wrote A to foo also wrote B to bar (before writing A to foo), you're guaranteed to see at least B in bar.

    Of course, if you never get to see A, you can't be guaranteed to see B either. And if you see B in bar, that says nothing about the visibility of A in foo. Also, the time that elapses between the thread writing A to foo and another thread seeing A in foo is not guaranteed.

提交回复
热议问题