This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
In this section the author discusses how a volatile field can be used to guarantee the ordering or reads and writes. Previously I'd thought this was only possible with synchronised. For example, the following code also guarantees that if v == true, then x == 42
My question is this: are there any differences in terms of thread safety, speed, etc. between the code I've shown above and that shown on the webpage? More generally, what are the advantages of using synchronized versus volatile to guarantee the ordering of reads/writes in a multithreaded program?
Cheers, DM [ January 30, 2007: Message edited by: Dan Murphy ]
Even when you synchronize your method, prior to java 5 the compiler may reorder the write instructions even if you mark a variable volatile. That is to say "v" may be marked true before x is marked to 42. For Java 5 and later, reordering of the writes is more strict when a variable is volatile. Thus you can now guarentee that "x" is 42 if "v" is true.
You would have to use synchronization for thread safety. Under some rare circumstances like the double check locking case in creation of singletons, you can now use volatile to be sure that instantiation happens properly. The JVM now guarantees that you wont get half instantiated objects because the reordering of instructions (or the lack of it ) is more strict.
Thanks for the read it was very interesting. I found a link to a java world page there and it talks about the JMM prior to java 5. Have a look at that too [ January 31, 2007: Message edited by: John Meyers ]