Wednesday, 4 November 2015

What are Volatile Variables?

A Volatile variable is modified asynchronously by concurrently running threads in a Java application. It is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have its data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.

When a field is declared volatile, the compiler and runtime  are  put on  notice  that  this  variable  is shared  and  that  operations  on  it  should  not  be  reordered  with  other memory operations.Volatile variables  are  not  cached  in  registers  or  in  caches  where  they  are  hidden  from  other processors, so a read of a volatile variable always returns the most recent write by any thread.

The most common use for volatile variables is as a completion, interruption, or status flag. Volatile variables can be used for other kinds of state information, but more care is required when attempting this. For example, the semantics of volatile are not strong enough to make the increment operation (count++) atomic, unless you can guarantee that the variable is written only from a single thread.

Note: Volatile variables can only guarantee visibility not atomicity.

Enjoy Reading.                                       

No comments:

Post a Comment