Possible Duplicate:
Is volatile expensive?
I heard that using volatile variable in multithreaded application brings some performance issues.
Does anybody explain why?
Possible Duplicate:
Is volatile expensive?
I heard that using volatile variable in multithreaded application brings some performance issues.
Does anybody explain why?
Declaring a variable as volatile
causes the JIT compiler to use instructions that read from / write to memory each time the variable is used. In the latter case, the cache-line has to be flushed to main memory do that other processors see the changes immediately. The read / write memory cycles to execution time.
By contrast, if you don't declare the variable as volatile, the JIT compiler may emit instructions to read / write the state of the variable from a register or from 1st or 2nd level memory cache. On average, this will save a few clock cycles for each read or write.
For a more detailed treatment read the answers to Is volatile expensive?.