Detailed semantics of volatile regarding timeliness of visibility

前端 未结 5 1755
北恋
北恋 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:25

    Please see this section (17.4.4). you have twisted the specification a bit, which is what is confusing you. the read/write specification for volatile variables says nothing about specific values, specifically:

    • A write to a volatile variable (§8.3.1.4) v synchronizes-with all subsequent reads of v by any thread (where subsequent is defined according to the synchronization order).

    UPDATE:

    As @AndrzejDoyle mentions, you could conceivably have thread r read a stale value as long as nothing else that thread does after that point establishes a synchronization point with thread w at some later point in the execution (as then you would be in violation of the spec). So yes, there is some wiggle room there, but thread r would be very restricted in what it could do (for instance, writing to System.out would establish a later sync point as most stream impls are synchronized).

提交回复
热议问题