Temple Wing
Temple Wing

Reputation: 433

Should every read for cross thread variable to be on volatile or Atomic or being wrapped by synchronization?

Can I say that if a variable can be modified by other thread, I can never safely read it without a memory barrier?

Upvotes: 2

Views: 248

Answers (1)

assylias
assylias

Reputation: 328608

Yes pretty much. If you write (w) to a variable in thread T1 and read (r) that same variable from thread T2, you need to have a happens-before relationship between (w) and (r) to get the guarantee that the result of (w) will be visible to (r). The Java Memory Model defines (JLS 17.4.5) the situations where there is a happens before relationship:

  • An unlock on a monitor happens-before every subsequent lock on that monitor.
  • A write to a volatile field (§8.3.1.4) happens-before every subsequent read of that field.
  • A call to start() on a thread happens-before any actions in the started thread.
  • All actions in a thread happen-before any other thread successfully returns from a join() on that thread.
  • The default initialization of any object happens-before any other actions (other than default-writes) of a program.

Upvotes: 2

Related Questions