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");


		try {
		} catch (InterruptedException e) {




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 🙂

9 thoughts on “A Practical scenario for using volatile in java

  1. You share interesting things here. I think that your page can go viral easily, but
    you must give it initial boost and i know how to do
    it, just search in google – mundillo traffic increase


  2. I have seen loads of useful elements on your site about pcs.
    However, I have the thoughts and opinions that notebooks are still more or less not
    powerful more than enough to be a sensible choice if you frequently do projects that require loads of power,
    for example video croping and editing. But for
    internet surfing, microsoft word processing, and majority of other common computer work they are just great, provided you do not mind the small screen size.
    Thank you sharing your thinking.


  3. Hello there, just became alert to your blog through Google, and found that it is really informative.

    Iཿm gonna watch out for brussels. I will be grateful
    if you continue this in future. Lots of people will be benefited from your writing.



  4. Class NumberFinder is not serving the purpose of volatile here, as its not being shared in all the threads. Its declared as instance variable here. Make it static as well guys…


    • Hey Amit,

      First of all, thanks for visiting my blog.
      This example is properly working without any issue, please send me your email id to connect and discuss in detail the issue you are facing with it.


  5. I see you don’t monetize bmegamind.com, don’t waste your traffic, you can earn extra cash every month
    with new monetization method. This is the best adsense alternative for any type of website (they approve all websites), for more details simply search in gooogle:
    murgrabia’s tools


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.