- The values of volatile variables will never be cached
- All read & writes will directly be done from main
memory
- Adding volatile variable is another way of making class
thread-safe
Volatile is useful when there are below
problems when volatile variables are not there
1. Memory Visibility: When one
thread modifies the value of a value it stored in a write buffer or cache. Processor
will push these buffered/cached values 'all at once' to main memory. This might
lead to data inconsistency, if there is not good 'cache coherence'.
2. Reordering: Reordering is an
optimization technique for performance improvement by processor or compiler.
For example, reader thread will see the updates to variables in any order other
than the actual program order
Using volatile keyword, we tell the runtime
& processor to not reorder these variables and immediately flush any
updates to these variables.
Volatile vs Synchronization:
Synchronized methods & blocks provide
'Mutual Exclusion' and 'Visibility' at the cost of application performance.
- Mutual Exclusion: Only one thread executes a critical
section at a time
- Visibility: Changes made by one thread to shared data
are visible to other threads to maintain data consistency
Volatile keyword ensures Visibility without Mutual Exclusion, thus it is useful when we are fine with
multiple threads accessing a block code parallel but we need to ensure data
visibility.
No comments:
Post a Comment