What is Volatile Keyword in java?

Volatile Keyword :

When we declare variable as Volatile in java it means that this variable is not stored in cache or in registers so they do not get hidden from the other processors or threads, they get stored in main memory and shared between processors.
As the operations on Volatile variable are done by many threads, this always returns most recent form of changed state.

So in simple words we can say that volatile variable has access of two different threads. As volatile keyword doesnt offer locking , we can say it as a lighter version of Synchronization.


volatile boolean STATUS;
....
while( !STATUS ){
proceedwithNext();
}



We can use Volatile keyword when indicating important event such as shutdown, exit from loop, initialization etc. So we can use them as completion, status or interruption flag.

But while using the Volatile keyword or rather to ensure that shared
variables are consistently and reliably updated we need to take care of some situations such as :
1. When Volatile keyword is being accessed, locking is not needed.
2. Volatile variable doesn't participate in operations with local variables.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment