Thursday, July 19, 2007

Using Volatile keyword efficiently

Java gives you a powerful keyword to address concurrent execution environments without writing your own mutual exclusion algorithm to monitor concurrent thread execution.


Though I must remind, this does come with some overheads and loss in efficiency, so before using volatile keyword one must fully understand the use, advantages and disadvantages of using volatile keyword.

What is Volatile?

Volatile is a Java modifier witch is a hint to the compiler about nature of the variable. It tells the compiler that given variable can be changed by something beyond the control of the program. It tells compiler to handle this variable differently than normal variables.

What different handling of Volatile variables done in Java?

When a variable is defined volatile, Java compiler and JVM do two things differently.

1. Compiler does not optimize the expressions and statements involving that variable.

2. Synchronization (concurrent execution with mutual exclusion) of the variable is done by JVM.

When to use Volatile and when to design your own monitor?

Now as we know volatile gives a hint to compiler that given variable can be changed by something beyond the control of the program, so then why Sun provided synchronization keyword.
As volatile keyword is handled by compiler and JVM, it involves some overheads and we don’t have control over handling of this critical section problem.

Thus when to use volatile and when to use custom monitors can be answered in this way:
Use Volatile keyword whenever the variable represents some type of system or environment dependent variable.
For Example: clocks and simple counters.

And use custom monitors for those variables witch are changed by some other code and not by the environment, or for those variables for witch you want greater control on concurrent execution.
For example: Linked List, Queues etc.


No comments: