RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Tip: Reading Updated/Latest Value in Multithreading Environment

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


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


Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date