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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. montoya says:

    could you please try it yourself and share the output with us

  2. The output like this..

    Thread 2 : 0
    Test Value 0
    Thread 1 : 0
    Thread 2 : 1
    Test Value 0
    Thread 1 : 1
    Thread 2 : 2
    Test Value 0
    Thread 1 : 2

    so the value only update for Thread 1 not for Thread 2, because not update in main of memory of variable..

  3. dhulipals says:

    this is not good example for Volatile :
    new ExampleThread(“Thread 1 “).start(); new ExampleThread(“Thread 2 “).start();—> here you are created TWO threads per TWO Objects( two threads not sharing any resource) ( volatile useful for “visibility” when 2 / more threads shares the same value/resource)
    class ExampleThread implements Runnable {
    volatile int testValue; // for visibilty
    private synchronized int incr(){ //for mutual exclusion return ++testValue;} public void run() { for (int i = 0; i < 3; i++) {
    try {
    if(Thread.currentThread().getName().equals("first"))
    System.out.println("first "+ incr());
    else
    System.out.println(Thread.currentThread().getName()+" "+incr());

    Thread.sleep(1000);
    } catch (Exception exception) {
    exception.printStackTrace();
    }
    }//end for
    }//end run
    } //end class

    public class VolatileExample {

    public static void main(String args[]) {
    ExampleThread v = new ExampleThread();
    new Thread(v, "six ").start();
    new Thread(v, "seven ").start();
    new Thread(v, "eight ").start();
    new Thread(v, "second").start();
    new Thread(v, "first").start();
    new Thread(v, "third").start();
    new Thread(v, "fourth").start();
    new Thread(v, "five").start();

    }

    }

    new ExampleThread("Thread 1 ").start(); new ExampleThread("Thread 2 ").start();

    • Agree, there has to be a shared resources for volatile to kick in. And in the post above there’s a new instance being created for each thread. Let me fix the post for you. Thanks for pointing it out.

    • if(Thread.currentThread().getName().equals(“first”))
      System.out.println(“first “+ incr());
      else
      System.out.println(Thread.currentThread().getName()+” “+incr());

      What have you done at there?
      “Thread 1″ is increments testValue, “Thread 2″ also doing the same. Still each threads updating their own copy only.

    • Nagaraju A says:

      same o/p came with volatile and without volatile
      can plz let me know what is d difference…?

  4. dhulipals says:

    class ExampleThread implements Runnable {
    volatile int testValue; // for visibilty
    private synchronized int incr(){ //for mutual exclusion return ++testValue;} public void run() { for (int i = 0; i < 3; i++) {
    try {
    if(Thread.currentThread().getName().equals("first"))
    System.out.println("first "+ incr());
    else
    System.out.println(Thread.currentThread().getName()+" "+incr());

    Thread.sleep(1000);
    } catch (Exception exception) {
    exception.printStackTrace();
    }
    }//end for
    }//end run
    } //end class

    public class VolatileExample {

    public static void main(String args[]) {
    ExampleThread v = new ExampleThread();
    new Thread(v, "six ").start();
    new Thread(v, "seven ").start();
    new Thread(v, "eight ").start();
    new Thread(v, "second").start();
    new Thread(v, "first").start();
    new Thread(v, "third").start();
    new Thread(v, "fourth").start();
    new Thread(v, "five").start();

    }

  5. dhulipal says:

    class ExampleThread implements Runnable {
    volatile int testValue; // for visibilty
    private synchronized int incr(){ //for mutual exclusion return ++testValue;} public void run() { for (int i = 0; i < 3; i++) {
    try {
    if(Thread.currentThread().getName().equals("first"))
    System.out.println("first "+ incr());
    else
    System.out.println(Thread.currentThread().getName()+" "+incr());

    Thread.sleep(1000);
    } catch (Exception exception) {
    exception.printStackTrace();
    }
    }//end for
    }//end run
    } //end class
    public class VolatileExample {
    public static void main(String args[]) {
    ExampleThread v = new ExampleThread();
    new Thread(v, "six ").start();
    new Thread(v, "seven ").start();
    new Thread(v, "eight ").start();
    new Thread(v, "second").start();
    new Thread(v, "first").start();
    new Thread(v, "third").start();
    new Thread(v, "fourth").start();
    new Thread(v, "five").start();
    }

  6. Mohit Soni says:

    i m executing the following code but the copy of volatile variable is being made separately for each thread. what what is the purpose of valatile variable.

    can anybody explain??

    class ExampleThread extends Thread
    {
    private volatile int testValue=0 ;
    public ExampleThread(String str)
    {
    super(str);
    }
    public void run()
    {
    if(getName().equalsIgnoreCase(“Thread 1″))
    {
    testValue++;
    System.out.println(testValue);
    }
    if(getName().equalsIgnoreCase(“Thread 2″))
    {

    System.out.println(testValue);
    }
    }
    public static void main(String args[])
    {
    new ExampleThread(“Thread 1″).start();
    new ExampleThread(“Thread 2″).start();
    }

    }

  7. naveen shukla says:

    Hello Everyone,

    I have run the example. But didn’t find any difference in Output. Please let me know what could be the reason.?

    Thanks

  8. Wrong Example

  9. puneet k agarwal says:

    As per my past experience and blogs I think the caching behavior which depends on the implementation on JVM.
    I have tried certain examples with server jvm which some times gives me the expected behavior and some times not.
    So i think caching of shared resource entirely depend on the JVM.

Trackbacks

  1. […] 原文地址:http://www.javabeat.net/2009/02/volatile-keyword-in-java/ […]

Speak Your Mind

*