dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


advertisement
 

Tip: Reading Updated/Latest Value in Multithreading Environment

Learn a good way to ensure that your variables show the most recently updated values.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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;
  }
}


 

Visit the DevX Tip Bank

 



   
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date