Thursday, 25 May 2017

28. Guarded Blocks and its types

1. Guarded block.
  1. Threads often have to coordinate their actions or result. The most common coordination idiom is the guarded block.
  2. Such a block begins by polling a condition that must be true before the block can proceed. There are a number of steps to follow in order to do this correctly.
  3. They are two types of guarded blocks
    1. Non Synchronized guarded block
    2. Synchronized guarded block
  4. If specified condition is true/false only the thread will execute further otherwise it resumes its execution.
  5. One thread uses the condition to check current thread need to execute or resume, but another thread update the condition if the specified work is done by second thread.
  6. So both threads will coordinate their actions by shared resource (boolean variable).

2. Non Synchronized Guarded block.
  1. In this case we simply cause the execution to keep executing a blank loop until the condition becomes true.
  2. This approach has an obvious disadvantage of wasting the precious CPU time, which could have been better utilized by some other threads otherwise.
public guardedBlock() {

while(!sharedBooleanFlag) {

   //... empty loop
}

System.out.println("Shared Boolean Flag is true - you may proceed now!");

}


3. Synchronized Guarded block.
  1. In this case if the condition is false then the block (which is a synchronized block) simply calls the Object.wait() method to release the acquired monitors on that object
  2. Thread leaves the processor to be used by other threads (probably more effectively as the current thread would not have done anything significant in this case unless the condition becomes true).

public synchronized guardedBlock() {

while(!sharedBooleanFlag) {
  try {
      wait();
  } catch (InterruptedException e) {}
}

System.out.println("Shared Boolean Flag is true - you may proceed now!");

}



No comments:

Post a Comment

3. Java Program to create Binary Tree