gomul gomul - 3 years ago 192
Java Question

Does the keyword volatile in Java force memory synchronization on single core machine?

If I understand it correctly, volatile is causing memory barrier that synchronises local memory with main memory. That is pretty useful on multi core machines.

Will this memory synchronisation happen when a multi threaded application is running on single core machine?

Answer Source

Will this memory synchronisation happen when a multi threaded application is running on single core machine?

Yes. volatile causes a read and/or write memory barrier and ensures a "happens-before" relationship when another thread is accessing the same volatile field. See this tutorial. It ensures that changes to the local CPU cache are written to main memory and that changes to main memory invalidate any CPU cache pages.

This is less important on a single-processor box since there is only one CPU cache to worry about. However, it is important to realize that the "happens-before" guarantees with volatile are still important. They prevent race conditions that could happen even if there is only one CPU because of time slicing with multiple threads.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download