Volatile keyword in Java

This tips explains the use of volatile keyword in Java. The keyword volatile is used in the multithreaded environment.

also read:

Local Variables in the Thread

If you are working with the multithreaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it’s updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn’t know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

Volatile Example

package javabeat.samples;
class ExampleThread extends Thread {
 private volatile int testValue;
  public ExampleThread(String str){
	super(str);
 }
 public void run() {
  for (int i = 0; i <; 3; i++) {
	try {
	 System.out.println(getName() + " : "+i);
	 if (getName().equals("Thread 1 ")){
		testValue = 10;
	}
	if (getName().equals("Thread 2 ")){
		System.out.println( "Test Value : "
		     + testValue);
	}
	Thread.sleep(1000);
	} catch (InterruptedException exception) {
		exception.printStackTrace();
	}
}
}
}
public class VolatileExample {
 public static void main(String args[]) {
  new ExampleThread("Thread 1 ").start();
  new ExampleThread("Thread 2 ").start();
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>