2

Possible Duplicate:
Is volatile expensive?

I heard that using volatile variable in multithreaded application brings some performance issues.

Does anybody explain why?

Community
  • 1
  • 1
user826323
  • 2,248
  • 6
  • 43
  • 70
  • 1
    Well, you need `volatile` (and/or `sync` and/or...) or you don't. Why is there even a question about "performance"? (Yes, synchronization/visibility guarantees adds some overhead.) –  Nov 03 '11 at 04:47
  • Reordering is prohibited and it can not be cached since it should be read from the main memory( for ensuring visiblity ) – Prince John Wesley Nov 03 '11 at 04:49

1 Answers1

6

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?.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • synchronized object (not volatile) updated by threads remain in thread's memory before it exits the synchronized block. But variable or object declared as volatile are directly written to the main memory. So is it expensive to write directly to the main memory when the volatile variable is updated by threads? Am I right? – user826323 Nov 03 '11 at 04:57
  • Yes, it is expensive. Is it >>more<< expensive? Depends on a wide range of factors. Too hard to predict in the general case. – Stephen C Aug 03 '15 at 22:36