Home  >  Core Java

Thread Communication Using Volatile in Java

By Arvind Rai, March 23, 2014
In java, volatile is thread safe variable. All the threads watch the most up-to-date value of the volatile variable automatically. Because of its visibility feature, volatile variable can be used for thread communication. Volatile variable is simple to use. Volatile keyword can be used as a flag for decision making. It can also be used for read write lock .

Use of Volatile

Find the example how to use a volatile variable in java program. We have two threads that are communicating each other using volatile variable. Here volatile has been used as flag.
VolatileTest.java
package com.concretepage;
public class VolatileTest {
    private static volatile boolean val = true;
    public static void main(String[] args) {
        new VolatileTest().new First().start();
        new VolatileTest().new Second().start();
    }
    class First extends Thread {
        @Override
        public void run() {
            while (true){
            	if(val){
	            	System.out.println("Thread one is working.");
	            	val=false;
            	}
            }
        }
    }
    class Second extends Thread{
        @Override
        public void run() {
           while (true){
        	   if(!val){
	        	   System.out.println("Thread two is working.");
	                try {
	                    Thread.sleep(1000);
	                } catch (InterruptedException e) { e.printStackTrace(); }
	                val=true;
        	   } 
            }
        }
    }
}
 
The output will be as below.
Thread one is working.
Thread two is working.
Thread one is working.
Thread two is working.
Thread one is working.
Thread two is working.
Thread one is working.
Thread two is working.
----------------------------------
---------------------------------
 
To check the effect if variable is not volatile then will it work the same, we remove the volatile keyword from the val variable in our program. We get the output as below.
Thread one is working.
Thread two is working.
 

Disadvantages of Using Volatile

1. Volatile keyword is weaker form of synchronization, we cannot use it as locking.
2. Volatile variable can be used as incremental counter because many threads working together may affect the value.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us