Friday, 22 April 2016

What could be the visibility issues in multithreading ?


There is no guarantee that the reading thread will see the value written by another thread on a timely basis or even at all. 

Example
public class A {
   private static boolean ready;
   private static class ReaderThread extends Thread {
      public void run() {
         while (!ready)    // READ VALUE
             Thread.yield();
         // -----
      }
   }
   public static void main(String[] args) {
        new ReaderThread().start();
        // ----- 
        ready = true;   // WRITE VALUE
   }
}


The value "ready" may not be seen in run method ; may be never.
So, while loop in run method could loop forever because the value of ready might never become visible to the reader thread.

Solution
Intrisic locks guarantees that one thread sees the effects of another.

When thread A executes a sync block and subsequently thread B enters a sync block guarded by the same lock,everything A did in or prior to a sync block is visible to B when it executes a sync block guarded by the same lock.

Locking also ensures memory visibility to ensure all threads see the most up-to-date values of shared (also mutable) variables.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.