A Practical scenario for using volatile in java

working example of “volatile” for Java7+ is a highly used searching keyword
for java guys. After lots of search people hardly get any working and effective
code on Volatile. So I decided to put one sample code here on Volatile.

A short note on volatile #
Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. Java guarantees that value of volatile variable will always be read from main memory and not from Thread’s local cache.So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. This guarantees visibility of changes made by one thread to another thread also.Java volatile keyword cannot be used with method or class
and it can only be used with variable. Java volatile keyword also guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.

Below is one example based on volatile, in which different Threads will try to search a number is different range if any thread finds the number search operation will be stopped by all Threads.

 public class SerachUsingVolatile {

	// search range starts with
	static int START = 0;
	static int END = 10000;

	public static void main(String[] args) {

		NumberFinder t = new NumberFinder(28000);

		Thread t1 = new Thread(t, "T1");
		Thread t2 = new Thread(t, "T2");
		Thread t3 = new Thread(t, "T3");

		t1.start();
		t3.start();

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		t2.start();

	}

}

class NumberFinder implements Runnable {
	//volatile boolean keepRunning = true;
        boolean keepRunning = true;
	int numToFind;

	NumberFinder(int nf) {
		this.numToFind = nf;
	}

	public void run() {

		int start = SerachUsingVolatile.START;
		int end = SerachUsingVolatile.END;

		// move range of search for each Thread
		SerachUsingVolatile.START = SerachUsingVolatile.START + 10000;
		SerachUsingVolatile.END = SerachUsingVolatile.END + 10000;

		while (keepRunning) {

			for (int i = start; i <= end; i++) {
				if (i == numToFind) {
					keepRunning = false;
					System.out.println("Target found by Thread: " + Thread.currentThread().getName()
							+ " rest all Threads should stop searching !!! ");
				}
			}
		}
		System.out.println(" Search stopped for Thread :" + Thread.currentThread().getName());
	}
}

**************************************************
Output with volatile :

Search stopped for Thread :T1
Target found by Thread: T2 rest all Threads should stop searching !!!
Search stopped for Thread :T3
Search stopped for Thread :T2

Output without volatile :

Target found by Thread: T2 rest all Threads should stop searching !!!
Search stopped for Thread :T2

*************************************************

That’s all Guys !!!! I am open for your questions n comment 🙂