#happens-before relations

1 messages · Page 1 of 1 (latest)

fierce nymph
#

If a variable is set in one thread, it may not be visible to other threads except the variable change "happens-before" the variable read.
One operation does not "happen-before" another solely because it is executed before the other operation but only if the JVM is told that the operation would need to logically be executed before another operation independently of timing or similar.
Operation A "happens-before" operation B if any of the following statements are true

  • Operation A "happens-before" any operation C that "happens-before" operation B
  • Operation A is releasing a lock and operation B is acquiring the same lock (e.g. an intrinsic lock (synchronized) or a synchronizer/lock from java.util.concurrent) after it operation A
  • Various thread-safe classes (especially in the package java.util.concurrent) also introduce a "happens-before"-relationship.
  • Both operations are run in the same thread and operation A is executed before operation B
  • Operation A "happens-before" starting the thread operation B is run in
    Changes to a variable that don't happen before reads of that variable may not be "seen" by the code reading the variable. This is because the JVM and the OS do various optimizations on multithreaded code.

The keyword volatile disables those optimizations on a variable in a way that every change to that variable is immediately visible to any other part of code reading the same variable afterwards.

However, this only works well on primitive and should not be used on reference types. Ignoring that can lead to references to unfinished/uninitialized objects escaping because the JVM/OS might still reorder instructions in order to improve performance. This may cause an assignment to be executed before the object is fully initialized.

The reason why volatile or other means of synchronization are needed for variable visibility is also pointed out in #1025480267114233949.

#

(copied from my answer to QOTW 71)

west valve
fierce nymph
#

probably :)