• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java memory model

 
Dan Murphy
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

This page here discusses the changes to the java memory model that were made in Java 5.0.

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 ]
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

[EDIT]

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 ]
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15482
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by John Meyers:
... Under some rare circumstances like the double check locking case in creation of singletons, ...

Just to warn you: Double-checked locking does not work. Don't use it.

http://en.wikipedia.org/wiki/Double-checked_locking
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
[ January 31, 2007: Message edited by: Jesper Young ]
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like I said prior to Java 5 double check locking does not work. But with the new rules for reordering writes for volatile variables being applied to Java 5, DCL will now work as expected.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic