Reading Updated/Latest Value in Multithreading Environment

In a multithreaded environment, there are always doubts about the latest value that a variable is holding, since there can be numerous thread instances updating, and also holding localized copies of the same variable, to consider.

Try to use the volatile keyword and the magic is visible. Using the volatile keyword for a variable ensures that the latest value of the variable is used for all computation purposes.

public class ThreadWithVolatileAttribute extends Thread {  //Defining a variable that needs to be monitored  private volatile boolean isJobCompleted = false;    //Thread's run method - performing activities based on the variable  public void run() {    while(!isJobCompleted) {      // Executing the task    }  }    //public method to update the state  public void setCompletedFlag() {   //Setting to true - Indicating the completion of the task   //This value will be used by the thread and conclude to continue with the task or exit the while loop.   isJobCompleted = true;  }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: