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.

Do you choose to throw NPE ?

Well, NPE the NullPointerException is quite famous among Java programmers. It has a bad impression although, no one want to see this in console but everyone for sure see this more than once while programming.

The agenda of this blog is whether we should throw NPE explicitly or not. Throwing exception is always better than swallowing it with try-catch and even more empty catch block is the worst thing you could have in your program.

Throwing NPE explicitly is valid, however, if you are getting something null in method parameter than we have another suitable exception which can be much more suitable and that is IllegalArgumentException.

According to the documentation, NPE is about depicting the use of null reference in program which is detected at runtime by JVM. If you could detect whether something is null in your program and want to throw NPE you are not raising it because of illegal use of null reference and actually throwing it before that.

So, we should always throw IllegalArgumentException instead of NPE if possible. I believe you will always go with this exception instead of NPE, but kindly note that throwing NPE is not a bad practice at all. Ultimate goal is to make your system report immediately if anything goes wrong instead of just continuing the execution.

Here better not to create a custom exception for such cases. Because if we already have inbuilt exception than why to create our own, so, don’t reinvent the wheel.