Volatile with example

Volatile is ignored or most of the times unknown concept among developers as we never(or hardly) use this keyword while building the programs.

I will try to express it in a simple term with an understandable (at least according to me) example. Before that volatile means (in Java context) liable to change rapidly.

Before volatile, we should understand why we need volatile. You know, each thread has it’s own stack (for optimization) where it can store variable used in it.

Now when variables are used among multiple threads it may be possible that one thread change the value and second would still use the old value which it has in it’s stack. Confusing!? if yes, then consider it like, each thread has it’s own memory to manipulate those variable and for the optimization sake it should not refer to the changes made by other threads.

So, what volatile keyword does ? It enforces “Java Memory Management Mechanism” to ensure that every thread can get a consistent value. Does that makes sense ? Indeed, I guess. But wait! volatile is not similar to synchronization and you can figure out that now.

Please refer to the following example.

class Counter extends Thread {
	
	private volatile long number = 0;
	
	@Override
	public void run() {
		while(number >= 0) {
			number++;
		}
		
		System.out.println("Counter is terminated! Number must be volatile.");
	}

	void terminate() {
		number = -999999999;
	}
}

class Tester extends Thread {

	@Override
	public void run() {
		Counter counter = new Counter();
		counter.start(); 

		try {
			System.out.println("Terminating the counter in 3 Seconds...");
			Thread.sleep(3000);
			counter.terminate();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class VolatileDemo extends Thread{

	public static void main(String[] args) {
		Tester tester = new Tester();
		tester.start();
	}
}

We will get following output with volatile

Terminating the counter in 3 Seconds...
Counter is terminated! Number must be volatile.

and following without volatile, (without volatile the program will keep on executing, so better to terminate it forcefully after observing the result for sometime.)

Terminating the counter in 3 Seconds...

To the best of my knowledge, use of volatile is too rare in day to day development. But it’s one of the hot topics in interviews due to it’s behavior.

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